将当前用户添加到模型表

时间:2012-09-02 12:22:36

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

如何在保存用户产品时将​​当前用户添加到user_product表。

我查看了一些在线信息,显示我可以将参数传递给构建方法,但这不起作用。错误消息是“无法批量分配受保护的属性:user_id”

产品总监:

def new

@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

类产品<的ActiveRecord ::基

    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

1 个答案:

答案 0 :(得分: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类定义模型名称(对它的引用虽然使用小写和下划线)。

相关问题