本文介绍了如何在创建时将数据传递到联接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下结构:

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还具有序列号行

However DeviceOwnership also has serial_number row

我想在创建时将serial_number值传递给DeviceOwnership.我知道我可以做类似的事情

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.

推荐答案

使用嵌套属性:

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"=>"[email protected]", "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.

这篇关于如何在创建时将数据传递到联接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-08 01:38