Rails拥有并属于许多重复条目

时间:2017-02-08 17:34:36

标签: ruby-on-rails postgresql rails-activerecord

我有2个模型和一个联接表(' email_addresses_mailable_events')。正在使用的数据库是Postgres。

class MailableEvent < ApplicationRecord
   has_and_belongs_to_many :email_addresses
end

class EmailAddress < ApplicationRecord
   has_and_belongs_to_many :mailable_events
   validates :address, uniqueness: true
end

假设有两个未保存的记录,{serial_number:&#39; 123&#39;,标记:&#39;测试&#39; }使用电子邮件地址[&#39; something@example.com',&#39; anything@example.com']和另一个,{serial_number:&#39; 456&#39;,标记:&# 39;测试&#39;使用相同的电子邮件地址[&#39; something@example.com',&#39; anything@example.com']

这些是从xml文件中解析的,我将这些保存为

...
email_address_array.each do |address|
   @email_address_obj = EmailAddress.find_by_address(address)
    unless @email_address_obj   
       @mailable_event.email_addresses.new(address: address,unsubscribe: false)  
       @mailable_event.save
    else
       @mailable_event.save
       event_fk = @mailable_event.id
       email_fk = @email_address_obj.id
       sql_insert = "INSERT INTO email_addresses_mailable_events(\"mailable_event_id\", \"email_address_id\") VALUES(#{event_fk},#{email_fk});"
       ActiveRecord::Base.connection.execute(sql_insert)
end

现在第一个将像往常一样提交到数据库表,但在保存第二个时,我将查找数据库中的电子邮件地址并将第二个MailableEvent记录与以下内容相关联:

> Look up first email address in email_addresses table and load it in.  # @email_address_obj = EmailAddress.find_by(address: 'something@gmail.com')

> Save the record({ serial number '456'}) associating it with 'something@example.com' too # @email_address_obj.mailable_events.create(@mailable_event.attributes)

> Look up second email address in EA table and load it in.  # @email_address_obj = EmailAddress.find_by(address: 'anything@example.com')

> Just associate the record({ serial number '456'}) with 'anything@example.com' # which means nothing has to be updated in Models and only a new entry { id: 'xx', EE_FK: 'xx', EA_FK: 'xx' } in join table has to be inserted, for which I cannot use @ea_object.mailable_events.create(@mailable_event.attributes) coz it will create a new duplicate EE record.

所以,我通过使用原始sql插入连接表来解决这个问题。但我仍然感到惊讶的是Rails无法处理这种情况。有没有使用原始SQL的rails方式?

0 个答案:

没有答案