无法正确复制其他模型的属性?

时间:2012-03-24 02:01:49

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

我有以下关联,然后在我的观察者中采取行动:

class Product < ActiveRecord::Base
  attr_accessible :price, :name, :watch_price
  belongs_to :user
  belongs_to :store
  has_many :product_subscriptions, :dependent => :destroy
  has_many :product_subscribers, :through => :product_subscriptions, :class_name => 'User'
end

class ProductSubscription < ActiveRecord::Base
  belongs_to :product
  belongs_to :product_subscriber, :class_name => 'User'
  attr_accessible :watched_price, :watched_name
end

class ProductObserver < ActiveRecord::Observer
 def after_create(product)
   ProductSubscription.new(product.attributes.merge({
       :watched_name => name,  
       :watched_price => price, 
       :store_id => :store_id,
      }))
  end
end

上面的代码使用ProductSubscriptionuser_id成功创建了product_id:watched_name:watched_price未填充原始{{1} }} Product:price

我注意到问题在于此。这没有任何意义,因为当我查看数据库时,它是按照我上面提到的那样分配的:

:name

现在我的其他字段是WARNING: Can't mass-assign protected attributes: product_id 模型的一部分而不是Product模型的一部分,所以可能是因为它而搞砸了?

我不希望ProductSubscription是可分配的。我怎么能纠正这个?

1 个答案:

答案 0 :(得分:2)

您的哈希值必须引用属性方法,而不是某些符号。这样,调用返回相应属性值的方法,并将值插入到散列中。你使用的符号没有任何意义。

ProductSubscription.new(product.attributes.merge({
    :watched_name => name,
    :watched_price => price, 
    :store_id => store_id,
  }))
end

此外,您似乎无法保存新的ProductSubscription。只是调用new不会将对象持久存储到数据库中。请改用create之类的内容。

最后,正如Andrew Marshall所说,你的数据库设计并不是最佳选择。复制整个表格行不会提供很好的性能。相反,您很快就会遇到不一致和使所有复制数据保持最新的麻烦。你真的应该学习联接和Database normalization

的概念