Rails关联模型未创建

时间:2013-10-03 15:43:18

标签: ruby-on-rails activerecord associations

我有以下协会:

class User < ActiveRecord::Base
  has_and_belongs_to_many :subscribers, :join_table => 'subscribers_users'
end

class Subscriber < ActiveRecord::Base
  has_and_belongs_to_many :devices, :join_table => 'subscribers_devices'
end

class Device < ActiveRecord::Base
  has_and_belongs_to_many :subscribers, :join_table => 'subscribers_devices'
  has_many :device_attributes
end

class DeviceAttribute < ActiveRecord::Base
  belongs_to :device
end

在用户类中,我的create方法如下所示:

def self.create(params)

  transaction do

    # create user
    user = User.new
    user.assign_attributes params

    # associate a device
    device = Device.build_from_params(params.dup)
    raise_if_invalid device
    subscriber.devices.push device

    # associate device_attributes to device
    params[:buttons].each do |b|
      # >>> problem here >>>
      device.device_attributes.build({:button_id => b[:button_id]})
    end

    user.save
  end

end

问题出现在创建设备的device_attributes对象的行上。注释此行时,将正确创建我的用户及其关联对象(订户和设备)。但是当我取消评论时,我的用户只有一个订阅者就是这样。它似乎停止并且不会与devce_attributes对象一起创建任何设备!

控制台没有错误..这对我来说真的很奇怪,出了什么问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

我相信您需要在循环中创建的每个Device对象上调用savebuild方法实例化一个新对象,但实际上并未将其保存到数据库中。有关详细信息,请参阅this guide

device.device_attributes.build({:button_id => b[:button_id]}).save()

current_device = device.device_attributes.build({:button_id => b[:button_id]})
current_device.save()

应该这样做。