Ruby on rails 4 注释模型未保存和显示:注释的正文部分
我是rails新手,在我的列表模型中添加评论系统时遇到了挑战。实际上,我有用户创建的列表,我希望能够允许其他用户对这些列表发表评论 到目前为止,我所拥有的: 一种列表模型,包括:Ruby on rails 4 注释模型未保存和显示:注释的正文部分,ruby-on-rails-4,params,comments,attr-accessible,Ruby On Rails 4,Params,Comments,Attr Accessible,我是rails新手,在我的列表模型中添加评论系统时遇到了挑战。实际上,我有用户创建的列表,我希望能够允许其他用户对这些列表发表评论 到目前为止,我所拥有的: 一种列表模型,包括: has_many :comments belongs_to :listing 注释模型,包括: has_many :comments belongs_to :listing 一名控制员: class CommentsController < ApplicationController def creat
has_many :comments
belongs_to :listing
注释模型,包括:
has_many :comments
belongs_to :listing
一名控制员:
class CommentsController < ApplicationController
def create
@listing = Listing.find(params[:listing_id])
@comment = @listing.comments.build(params[:body]) # ***I suspected that I needed to pass :comment as the params, but this throws an error. I can only get it to pass with :body ***
respond_to do |format|
if @comment.save
format.html { redirect_to @listing, notice: "Comment was successfully created" }
format.json { render json: @listing, status: :created, location: @comment }
else
format.html { render action: "new" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
end
def comment_params
params.require(:comment).permit(:body, :listing_id)
end
class CommentsController
最后是一个列表视图,其中包含以下用于收集和显示注释的代码:
<div class="form-group">
<%= form_for [@listing, Comment.new] do |f| %>
<%= f.label :comments %>
<%= f.text_area :body, :placeholder => "Tell us what you think", class: "form-control", :rows => "3" %>
<p><%= f.submit "Add comment", class: "btn btn-primary" %></p>
<% end %>
</div>
<%= simple_form_for [@listing, Comment.new] do |f| %>
<p>
<%= f.input :body, :label => "New comment", as: :text, input_html: { rows: "3" } %>
</p>
<p><%= f.submit "Add comment", class: "btn btn-primary" %></p>
<% end %>
“告诉我们您的想法”,类:“表单控件”,行=>“3”%>
“新评论”,如::文本,输入_html:{行:“3”}%>
评论框在视图中正确显示,我可以提交评论,但是:正文似乎没有保存,因此“x分钟前提交”是我评论部分中唯一显示的内容
有没有关于我可能做得不对的想法?我怀疑这是params的问题,但一直没能解决
谢谢 由于您在Rails 4中使用的是strong_parameters范例,我认为您应该将注释创建行更改为:
@comment = @listing.comments.build(comment_params)
@listing = Listing.find(params.permit(:listing_id))
我将列表查找行更改为:
@comment = @listing.comments.build(comment_params)
@listing = Listing.find(params.permit(:listing_id))
只要您在
comment\u params
方法中正确地将所有必需的参数列为白名单,它就可以正常工作。非常感谢您的帮助!@comment=@listing.comments.build(comment\u params)更改列表查找时抛出了一个错误,因此只需要更改comment\u parms。