Рельсы проверяют дубликаты sub-ha sh перед ассоциацией - PullRequest
0 голосов
/ 21 апреля 2020

Мне нужно добавить запись (объект Keyword) в список связанных объектов (item.keywords).

Чтобы иметь дубликат, я должен проверить, есть ли уже записи с такими же полями " text, match_type and state "и, в случае, игнорировать вставку. Я не могу проверить «точное совпадение» двух записей, потому что другие поля отличаются (например, otherfield1,2,3).

Я искал что-то вроде item.keywords.include?({text: text, match_type: type, state: state})

модель

Class Item < ApplicationRecord
    has_many :keywords, dependent: :destroy

код

def copyTo(item)

    text =  'AB'; match_type = 'XYZ'; state = 'DEW'

    item.keywords << Keyword.new(
       text: text,
       match_type: type,
       state: state
    ) unless item.keywords.include?({text: text, match_type: type, state: state}) # <--- HERE
end

схема

 create_table "keywords", force: :cascade do |t|
    t.bigint "otherfield"
    t.string "otherfield2"
    t.string "otherfield3"
    t.string "state"
    t.string "text"
    t.string "match_type"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "item_id"
  end

1 Ответ

1 голос
/ 21 апреля 2020

Используйте find_or_create_by. Я только что изменил твой код.

def copyTo(item)
  text =  'AB'; match_type = 'XYZ'; state = 'DEW'

  item.keywords.find_or_create_by(
    text: text,
    match_type: type,
    state: state
  )
end
...