注释控制器中的ActiveModel :: ForbiddenAttributesError

use*_*030 2 ruby-on-rails strong-parameters

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

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

 @comment = @commentable.comments.new(params[:comment]) <--- Fail here
Run Code Online (Sandbox Code Playgroud)

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>
  >>
Run Code Online (Sandbox Code Playgroud)

评论控制器:

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
Run Code Online (Sandbox Code Playgroud)

结束

   def comments_params
       params.require(:comments).permit(:commentable, :product_id, :content)
   end
Run Code Online (Sandbox Code Playgroud)

产品控制器:

  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
Run Code Online (Sandbox Code Playgroud)

型号:product.rb

   class Product < ActiveRecord::Base

       has_many :comments, as: :commentable 
       accepts_nested_attributes_for :comments
   end
Run Code Online (Sandbox Code Playgroud)

comment.rb

   class Comment < ActiveRecord::Base

       belongs_to :commentable, polymorphic: true

   end
Run Code Online (Sandbox Code Playgroud)

Kir*_*rat 6

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

更换

@comment = @commentable.comments.new(params[:comment]) 
Run Code Online (Sandbox Code Playgroud)

@comment = @commentable.comments.new(comments_params) 
Run Code Online (Sandbox Code Playgroud)

另外,更新comments_params如下

  def comments_params
       params.require(:comment).permit(:commentable, :product_id, :content)
   end
Run Code Online (Sandbox Code Playgroud)

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