我有以下结构:
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
然而,DeviceOwnership也有serial_number行
我想在创建时将serial_number值传递给DeviceOwnership。我知道我可以做类似
的事情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
这似乎不太优雅,我想知道是否有更好的解决方案。
答案 0 :(得分:3)
使用嵌套属性:
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
现在,如果您的参数是这样的话,您可以在事务中一次保存所有关联:
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.