[英]How to create has_many :through association and set join model attributes
我有这些模特
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)
...但是当我应该已经引用了它时,查询我刚刚创建的记录似乎很愚蠢。
在为发行版本创建新的记录记录的同时,如何设置位置字段?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.