【问题标题】:add current user to model table将当前用户添加到模型表
【发布时间】:2012-08-27 11:38:43
【问题描述】:

保存用户产品时如何将当前用户添加到 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

类产品<: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

【问题讨论】:

  • @samironpaul....嘿是帖子
  • 你的问题有点含糊,你能解释一下“有效地设置这些模型”是什么意思吗?
  • @Beerlington 我只是在询问设置模型的最佳方法
  • 不完全是这个问题的答案,但你看过 spree 吗? github.com/spree/spree,这是一个很棒的基于 RoR 的开源应用程序,用于购物车和结帐
  • 我已经看过了...我打算将它用于购物车和结帐...但是这个问题只是为了满足正确设置我的模型之间的关联...谢谢再次

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


【解决方案1】:

我建议如下:

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 对此非常挑剔。如果您没有正确使用 rails 约定,则代码将无法正常工作(更糟糕的是,您将开始编写黑客来解决感知到的“问题”),例如 User_Product 应该是 UserProduct (或我的答案中的 Preference )而不是 User_Product - 因为类定义模型名称(对它的引用使用小写和下划线)。

【讨论】:

  • @MichaelDurrant...照片实际上应该属于用户的列表(Preference 模型)...
猜你喜欢
  • 1970-01-01
  • 2021-01-12
  • 2020-11-10
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 2017-05-08
相关资源
最近更新 更多