问题
I have the following structure:
class User < ActiveRecord::Base
has_many :device_ownerships
has_many :devices, :through => :device_ownerships
end
class Device < ActiveRecord::Base
has_one :device_ownership
has_one :user, :through => :device_ownership
end
class DeviceOwnership < ActiveRecord::Base
belongs_to :user
belongs_to :device
end
However DeviceOwnership also has serial_number row
I want to pass serial_number value to DeviceOwnership on create. I understand I can do something like
def create
user = User.create
device = Device.create
device_ownership = DeviceOwnership.create(:serial_numer => params[:device_serial_number], :device_id => device.id, :user_id => user.id)
end
This does not seem too elegant, I wonder if there is a better solution.
回答1:
Use nested attributes:
class User < ActiveRecord::Base
has_many :device_ownerships
has_many :devices, :through => :device_ownerships
accepts_nested_attributes_for :devices
end
class Device < ActiveRecord::Base
has_one :device_ownership
has_one :user, :through => :device_ownership
accepts_nested_attributes_for :device_ownership
def device_ownership_attributes=(attributes)
dev = build_device_ownership(attributes)
dev.user = self.user
end
end
class DeviceOwnership < ActiveRecord::Base
belongs_to :user
belongs_to :device
end
Now you can save all associations at once with in a transaction if your params are like this:
pramas = {"user"=>{ "email"=>"user@example.com", "devices_attributes" =>{"0"=>{"name" => "Devise 1", "device_ownership_attributes"=>{"device_serial_number"=>"xyz"}}}}
user = User.create(params['user'])
# will save User, devise, and devise ownership all at once.
来源:https://stackoverflow.com/questions/25941440/how-to-pass-data-to-join-table-on-creation