sparkle
sparkle

Reputation: 7390

Rails check duplicate sub-hash before association

I have to add a record (Keyword object) to a list of associated objects (item.keywords).

To have duplicate I have to check before if there is already a records with the same fields "text, match_type and state" and, in case, ignore the insertion. I cannot check for "exact match" of two records because other fields are different (es. otherfield1,2,3).

I was looking for something like item.keywords.include?({text: text, match_type: type, state: state})

model

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

code

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

schema

 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

Upvotes: 0

Views: 36

Answers (1)

Amit Patel
Amit Patel

Reputation: 15985

Use find_or_create_by. I just modified your code.

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

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

Upvotes: 1

Related Questions