我想在书中添加评论(评论属于书),所以我添加了此表单以显示书页:
%h3 Add a comment:
= form_with(model: [ @book, @book.comments.build ], local: true) do |form|
%p
= form.text_area :content
%p
= form.submit "Add a comment"
它可以工作,但是我需要显示模型验证错误以获取空注释。我尝试过:
- if @book.errors.any?
%h2
= pluralize(@book.errors.count, "error")
prohibited this article from being saved:
%ul
- @book.errors.full_messages.each do |msg|
%li= msg
(在“ form_with”行之后),但没有任何反应。我认为@ book.errors是错误的,但是不知道如何替换它。
我的评论控制器的创建方法:
def create
@book = Book.find(params[:book_id])
@comment = @book.comments.create(comment_params)
@comment.user = current_user
if @comment.save
redirect_to book_path(@book)
end
end
答案 0 :(得分:0)
1> comments_controller.rb
@GetMapping("/edit/{id}")
public void edit(@PathVariable("id") int id, Principal principal) {
User u = (User) userDetailsService.loadUserByUsername(principal.getName());
if(u.getId() == id || u.getRoles().contains("ADMIN")) {
//accept uer
}
}
2>将 def create
@book = Book.find(params[:book_id])
@comment = @book.comments.create(comment_params)
@comment.user = current_user
if @comment.save
redirect_to book_path(@book)
else
redirect_back(fallback_location: book_path(@book))
end
end
替换为@book
,因为@comment对象包含验证错误
@comment