2
我有一個評論控制器和一個產品控制器。它在帶有Forbidden Attributes錯誤的評論控制器的創建操作上失敗。評論控制器中的ActiveModel :: ForbiddenAttributesError
我已經從模型中刪除了所有attr_accessible,並將它們移動到控制器。仍然有一些錯誤。我無法弄清楚什麼。請任何人都可以告訴我我錯過了什麼。
@comment = @commentable.comments.new(params[:comment]) <--- Fail here
從更好的錯誤
外殼帶電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
是的,它的Rails 4.0。我嘗試了你的建議。 它似乎沒有工作。如果我這樣說:param找不到:評論 – user2511030
@ user2511030檢查更新的答案 –
Kirti!這確實奏效。請你能告訴我我做得不對嗎? – user2511030