2012-03-24 48 views
0

我有以下的關聯,然後行動,我觀察報:上述無法正確複製其他模型的屬性?

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_idproduct_id:watched_name:watched_price沒有充滿原始Product:price:name

我注意到問題在於此。這沒有任何意義,因爲當我看着在數據庫中,它被分配正如我上面提到:

WARNING: Can't mass-assign protected attributes: product_id 

現在我有其他的領域是分開Product模型是不分開的ProductSubscription模型所以也許它因此而搞砸了?

我不希望product_id是可分配的。我怎麼能糾正這個?

+0

爲什麼ProductSubscription首先有產品屬性的重複? – 2012-03-24 02:35:03

+0

@AndrewMarshall我使用ProductSubscription來「觀察」較低的價格,方法是首先複製產品的屬性,然後將複製的屬性與其他類似的產品進行比較。 – LearningRoR 2012-03-24 02:38:30

回答

2

您的散列值必須引用屬性方法,而不是某些符號。這樣,返回相應屬性值的方法被調用,並將值插入到散列中。你使用的符號沒有任何意義。

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

而且,你似乎不保存新ProductSubscription。只要調用new就不會將對象保存到數據庫中。改爲使用類似create的東西。

最後,正如Andrew Marshall所說,你的數據庫設計並不是最優的。複製整個表格行不會提供很好的性能。相反,您很快就會遇到不一致以及保持所有複製數據保持最新狀態的麻煩。你真的應該學習關於連接和Database normalization的概念

相關問題