2012-09-02 48 views
0

如何在保存用戶產品時將​​當前用戶添加到user_product表中。將當前用戶添加到模型表

我在網上查看了一些信息,顯示我可以將參數傳遞給構建方法,但這不起作用。該錯誤消息是這個 「不能大規模指派保護屬性:USER_ID」

產品控制器:

高清新

@product = Product.new 

@product.user_products.build(:user_id => current_user) 

respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @product } 
end 

我的型號有:ProductUserUser_Product

class產品< ActiveRecord :: Base

attr_accessible :name, :issn, :category, :user_products_attributes 

    validates_presence_of :name, :issn, :category 
    validates_numericality_of :issn, :message => "has to be a number" 

    has_many :user_products 
    has_many :users, :through => :user_products 

    accepts_nested_attributes_for :user_products 

end 




class UserProduct < ActiveRecord::Base 

    attr_accessible :price 

    validates_presence_of :price 
    validates_numericality_of :price, :message => "has to be a number" 

    belongs_to :user 
    belongs_to :product 

end 

class user < ActiveRecord::Base 

    # devise authentication here 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me 

    has_many :user_products, :dependent => :destroy 
    has_many :products, :through => :user_products 

end 
+0

@samironpaul ....嘿是這個職位 – justcode

+0

你的問題有點含糊,你能解釋一下「有效地設置這些模型」是什麼意思嗎? –

+0

@Beerlington我只是要求建立模型 – justcode

回答

0

我建議如下:

Product 
    has_many :preferences 
    has_many :users, :through => preferences 
    has_one :product_photo # if 1 per product 

User 
    has_many :preferences 
    has_many :products, :through => :preferences 

Preference 
    belongs_to :user 
    belongs_to :product 

ProductPhoto 
    belongs_to :product 

不管你做什麼,一定要注意大小寫和軌道多元化是相當挑剔一番。如果你沒有正確的使用Rails約定,代碼將無法工作(更糟糕的是,你將開始編寫黑客來解決感知的問題),例如User_Product應該是UserProduct(或者我的回答中的首選項)而不是User_Product - for類定義模型名稱(引用它使用小寫和下劃線雖然)。

+0

@MichaelDurrant ...照片實際上應該屬於用戶的列表(偏好模型)... – justcode