评论不会保存到个人资料
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了评论不会保存到个人资料相关的知识,希望对你有一定的参考价值。
我可以在用户个人资料上填写评论表格:
user_profile_reviews POST /users/:user_id/profiles/:profile_id/reviews(.:format) reviews#create
new_user_profile_review GET /users/:user_id/profiles/:profile_id/reviews/new(.:format) reviews#new
实际上,代码在我收到我在Reviews Controller中定义的错误消息时以某种方式工作了
class ReviewsController < ApplicationController
before_action :set_profile
before_action :set_review, only: :new
def new
@review = Review.new
end
def create
@profile = Profile.find(params[:profile_id])
@review = @profile.reviews.build(review_params)
@review.user_id = current_user.id
if @review.save
redirect_to user_profile_path(current_user, @profile)
else
redirect_to user_profile_path(current_user, @profile), notice: "Didn't save your review"
end
end
private
def review_params
params.permit(:content, :rating)
end
def set_profile
@profile = Profile.find(params[:profile_id])
end
def set_review
@review = Review.find(params[:id])
end
end
提交后,我得到:“没有保存您的评论”,因此创建方法有效,但只有一半。为什么不节省呢?我该如何纠正?非常感谢!非常感谢您的帮助!
P.S。这是我的表格:
<div class="submit-review">
<%= form_for([@user, @profile, @review], :url => user_profile_reviews_path(@user, @profile)) do |f| %>
<label for="review">How was your experience?</label><br>
<%= f.label :rating %>
<%= f.select :rating, options_for_select([["Please select one", ""], 5, 4, 3, 2, 1]) %>
<%= f.text_area :content, placeholder:"Please enter your feedback here" %>
<%= f.submit "Submit your review", class: "btn btn-default" %> <br><br>
<% end %>
答案
看来许可参数存在问题。
您需要指定参数键:review
。类似于:
def review_params
params.fetch(:review, {}).permit(:rating, :content)
end
也可能是某些验证失败。我建议在else
中使用渲染,而不要重定向。因此,如果验证失败,您可以呈现错误消息。
以上是关于评论不会保存到个人资料的主要内容,如果未能解决你的问题,请参考以下文章