我有以下关联,然后在我的观察者中采取行动:
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
上面的代码使用ProductSubscription
和user_id
成功创建了product_id
但:watched_name
和:watched_price
未填充原始{{1} }} Product
和:price
。
我注意到问题在于此。这没有任何意义,因为当我查看数据库时,它是按照我上面提到的那样分配的:
:name
现在我的其他字段是WARNING: Can't mass-assign protected attributes: product_id
模型的一部分而不是Product
模型的一部分,所以可能是因为它而搞砸了?
我不希望ProductSubscription
是可分配的。我怎么能纠正这个?
答案 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
的概念