[英]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.