如何创建has_many:通过关联并设置连接模型属性

时间:2014-02-03 06:31:38

标签: ruby-on-rails rails-activerecord

我有这些模型

class Release < ActiveRecord::Base
  has_many :recordings, through: :release_recordings
  has_many :release_recordings, inverse_of: :release
end

class Recording < ActiveRecord::Base
  has_many :releases, through: :release_recordings
  has_many :release_recordings, inverse_of: :recording

  accepts_nested_attributes_for :release_recordings
end

class ReleaseRecording < ActiveRecord::Base
  belongs_to :release
  belongs_to :recording
end

我想以这种方式创建我的录音,在连接表中添加position条目:

release.recordings.create!(name: name, release_recordings_attributes: { 0 => {position: position} })

问题是这最终会尝试在release_recordings表中创建两条记录。一个release_idNULL,另一个positionNULL。当然,我只想创建一个没有任何NULL字段的记录。

我最终这样做了(它按预期工作):

recording = release.recordings.create!(name: name)
recording.release_recordings.find_by_release_id(release).update_attributes!(position: position)

...但是当我已经创建了我刚刚创建的录制内容时,查看我刚刚创建的录制内容似乎很愚蠢。

如何在为发布创建新录制记录的同时设置位置字段?

1 个答案:

答案 0 :(得分:0)

release.recordings.create!(name: name).release_recordings.create(position: position)

不确定这是否有效..

class Recording < ActiveRecord::Base
  has_many :releases, through: :release_recordings
  has_many :release_recordings, inverse_of: :recording

  accepts_nested_attributes_for :release_recordings, reject_if: lambda { |release_recording| release_recording['release_id'].blank? }
end