我有这些模型
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_id
为NULL
,另一个position
为NULL
。当然,我只想创建一个没有任何NULL
字段的记录。
我最终这样做了(它按预期工作):
recording = release.recordings.create!(name: name)
recording.release_recordings.find_by_release_id(release).update_attributes!(position: position)
...但是当我已经创建了我刚刚创建的录制内容时,查看我刚刚创建的录制内容似乎很愚蠢。
如何在为发布创建新录制记录的同时设置位置字段?
答案 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