简体   繁体   中英

How to create has_many :through association and set join model attributes

I have these models

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

I want to create my recordings in this manner, adding a position entry to the join table:

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

The problem is that this ends up trying to create two records in the release_recordings table. One where the release_id is NULL and one where the position is NULL . Of course, I only want to create one record without any NULL fields.

I ended up doing this (and it works as intended):

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

...but it seems silly to go and query for the recording I just created when I should have a reference to it already.

How can I set the position field at the same time I'm creating a new recording record for the release?

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

not sure this will work or not..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM