注释控制器中的ActiveModel :: ForbiddenAttributesError

时间:2014-02-24 17:33:25

标签: ruby-on-rails strong-parameters

我有一个评论控制器和一个产品控制器。它在带有Forbidden Attributes错误的注释控制器的创建操作时失败。

我已从模型中删除了所有attr_accessible并将它们移动到控制器。还是有些不对劲。我无法弄清楚是什么。请任何人都可以告诉我我错过了什么。

 @comment = @commentable.comments.new(params[:comment]) <--- Fail here

来自更好错误的Live Shell o / p:

   >> params[:comment]
   => {"content"=>"thanks"}

   >> @commentable
   => #<Product id: 1, title: "Coffee Mug", description: "<p> This coffee mug blah blah", image_url: "http://coffee.com/en/8/82/The_P...", price: #<BigDecimal:7ff8769a9e00,'0.999E1',18(45)>, tags: nil, created_at: "2014-02-24 14:49:34", updated_at: "2014-02-24 14:49:34">

  >> @commentable.comments
  => #<ActiveRecord::Associations::CollectionProxy []>


  >> @commentable.comments.new(params[:comment])
  !! #<ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError>
  >>

评论控制器:

class CommentsController < ApplicationController

 def new
  @comment = @commentable.comments.new
end

def create
 @comment = @commentable.comments.new(params[:comment]) <-- fail here
 if @comment.save
      redirect_to product_path(params[:product_id])
 else
      render :new
 end

   def comments_params
       params.require(:comments).permit(:commentable, :product_id, :content)
   end

产品总监:

  class ProductsController < ApplicationController

   def show
    @product = Product.find(params[:id])
    @commentable =  @product
    @comments ||= Comment.where(:commentable_id => params[:id])
    @comment = Comment.new
   end

   def product_params
       params.require(:product).permit(:title, :description, :image_url, :price, :tags, comments_attributes: [:product_id, :content])
   end

型号: product.rb

   class Product < ActiveRecord::Base

       has_many :comments, as: :commentable 
       accepts_nested_attributes_for :comments
   end

comment.rb

   class Comment < ActiveRecord::Base

       belongs_to :commentable, polymorphic: true

   end

1 个答案:

答案 0 :(得分:6)

我猜你正在使用Rails4,因为你实现了comments_params方法。 在Rails 4中,强参数用于将质量分配保护移出模型并进入控制器。您已实现方法comments_params但未使用它。

替换

@comment = @commentable.comments.new(params[:comment]) 

@comment = @commentable.comments.new(comments_params) 

另外,请按以下步骤更新comments_params

  def comments_params
       params.require(:comment).permit(:commentable, :product_id, :content)
   end

注意:需要单数:comment而不是复数:comments