我正在为每个railscasts第154集构建一个多态评论系统。我似乎无法获得接受正确字段的强参数。在POST操作中,参数如下所示:
{"utf8"=>"✓",
"authenticity_token"=>"/yVWatJSRY1AmAqgbS4Z9S8kIlfQAKBbUeHc/5coxeM=",
"comment"=>{"content"=>"Hello"},
"commit"=>"Create Comment",
"user_id"=>"1"}
我的MVC我将在下面发布。有没有人知道在这种情况下使用强参数的正确方法?
型号:
class Link < ActiveRecord::Base
has_many :votes
belongs_to :user
has_many :comments, as: :commentable
end
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
控制器
class CommentsController < ApplicationController
before_action :load_commentable
def index
@comments = @commentable.comments
end
def new
@comment = @commentable.comments.new
end
def create
@comment = @commentable.comments.new(params.require(:comment [:content]))
if @comment.save
redirect_to [@commentable, :comments], notice: "Comment created."
else
render :new
end
end
def load_commentable
resource, id = request.path.split('/')[1,2]
@commentable = resource.singularize.classify.constantize.find(id)
end
end
查看
<h1>New Comment</h1>
<%= form_for [@commentable, @comment] do |f| %>
<% if @comment.errors.any? %>
<div class="error_messages">
<h2>Please correct the following errors.</h2>
<ul><% @comment.errors.full_messages.each do |msg| %>
<li><%= msg %>
<% end %>
</ul>
</div>
<% end %>
<div class="field" >
<%= f.text_area :content, rows: 8 %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:3)
就强大的障碍而言,它应该与任何其他控制器不同。
确实
@comment = @commentable.comments.new(params.require(:comment).permit(:content))
不行吗?