Rails 4 には strong_parameters が付属しており、これは素晴らしい追加機能ですが、私はそれで問題に遭遇しました。私はポリモーフィックなモデルを持っていComment
ますが、コントローラーが必要なパラメーターを受け入れることは一生できません。これが私のコードです(わかりやすくするために短縮されています):
ルート:
resources :articles do
resources :comments
end
モデル:
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
コントローラ:
class CommentsController < ApplicationController
before_action :get_commentable
def create
@comment = @commentable.comments.new(comment_params)
if @comment.save
redirect_to @commentable, :notice => "Thank you!"
else
render :new
end
end
private
def get_commentable
resource, id = request.path.split("/")[1,2]
@commentable = resource.singularize.classify.constantize.find(id)
redirect_to :home unless defined?(@commentable)
end
def comment_params
params.require(:comment).permit(:title, :message)
end
end
投稿されたパラメーター (articles#show のフォームから):
{"authenticity_token"=>"v70nN8aFpofNw9vbVjhpsm9SwLOwKlOpNOEOTozUwCk=",
"comment"=>{"title"=>"Test","message"=>"Testing"},
"article_id"=>"1"}
私にはそれがうまくいくように見えますが、私が何をしようActiveModel::ForbiddenAttributesError in CommentsController#create
としても、私が試しても
def comment_params
params.permit!
end
コントローラーで。他の (非ポリモーフィック) モデルではそのような問題はありません。そのため、ポリモーフィズムと関係があると思われます。何か案は?