且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在创建时将数据传递到联接表

更新时间:2023-12-03 16:09:10

使用嵌套属性:

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.