我可以在用户个人资料上填写评论表格:
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
实际上,当我收到我在“评论控制器”中定义的错误消息时,代码以某种方式起作用了
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 %>
答案 0 :(得分:2)
看起来参数存在问题。
您需要指定参数键:review
。像这样:
def review_params
params.fetch(:review, {}).permit(:rating, :content)
end
也可能是某些验证失败。我建议在else
中使用渲染,而不要重定向。因此,如果验证失败,您可以呈现错误消息。