0
我正在爲每個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 %>