【问题标题】:Rails: How to create a new entry in the join tableRails:如何在连接表中创建新条目
【发布时间】:2012-08-30 12:54:16
【问题描述】:

让我们考虑一个实际示例:由客户撰写的有很多评论的产品。我们通过 reviewsproductclient 之间建立了多对多的关系。

class Product < ActiveRecord::Base
    has_many :reviews
    has_many :clients, :through => :reviews
end

class Client < ActiveRecord::Base
    has_many :reviews
    has_many :products, :through => :reviews
end

class Reviews < ActiveRecord::Base
    belongs_to :product
    belongs_to :client
end

这里,我使用has_many :through 来创建多对多关系,因为review 表需要有额外的属性,比如分数、内容、喜欢... .

用户登录我的应用,我可以通过以下方式获取他的数据:

client = Client.find_by_id current_user.id

他去产品页面,所以我可以得到产品数据:

product = Product.find_by_id params[:id]

如何创建产品的客户评论?

我试过了:

review = Review.create :client => client, :product => product, :comment => params[:review][:comment]

但它给了我:MassAssignSecurity:无法批量分配受保护的属性:产品、客户

有什么想法吗?提前致谢。

【问题讨论】:

    标签: ruby-on-rails many-to-many model-associations


    【解决方案1】:

    创建 Review 对象并显式传递参数后,您需要使它们在 Review 模型中可访问。在这种情况下,它必须是外键

    class Reviews < ActiveRecord::Base
    
        belongs_to :product
        belongs_to :client
    
        attr_accessible :client_id, :product_id
    end
    

    这应该可行,但这是不好的做法,会导致安全问题。我建议不要让外键可访问并在 Review.create 中显式传递它们,而是将 review.create 替换为以下内容:

    review = Review.new
    review.client = client
    review.product = product
    review.comment = params[:review][:comment]
    review.save
    

    这将创建一个新的 Review 对象,避免批量分配。 希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      添加到你的模型,其中属性是 :product 和 :client

      attr_accessible :product, :client
      

      http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html

      【讨论】:

      • 感谢您的回复 prasad,但不幸的是,即使我在 Review 模型中添加了attr_accessible :product, :client,它仍然不起作用。我正在使用 rails 控制台 (rails c) 进行测试。
      • 修改模型后有reload!吗?
      【解决方案3】:

      :client 和 :product 属性是私有的,您必须让它们分别在每个类设置 attr_accessible :clientattr_accessible :product 上可访问,例如:

      class Reviews < ActiveRecord::Base
          belongs_to :product
          belongs_to :client
      
          attr_accessible :client, :product
      end
      

      希望对你有帮助

      【讨论】:

      • 谢谢 Vilem。当我写信给 prasad 时,它仍然不起作用,即使我将 attr_accessible :product, :client 添加到 Review 模型中。
      • 我认为您必须将 attr_accessible 添加到您的类中,而不是在模型模型中。
      • 对不起,我不明白。请您更准确一点,通过更新您的答案,使用代码来解释哪个attr_accessible :xxx 属于哪个模型Xxx
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多