向现有视图添加评论的正确方法 rails

Correct way to add a comments to existing view rails

我有一个 rails 应用程序,它有一个脚手架,可以通过控制器显示操作显示图像。我想为每张图片添加评论。这样做的正确方法是什么?我尝试制作第二个控制器+模型+视图,在图像显示视图中呈现部分评论形式,并通过参数传递图像 ID。它有效,但我不认为这是应该如何完成的。如果您知道一个很好的示例项目可以实现这样的功能,请将它发送给我,我找不到任何东西。感谢您的帮助。

这通常由 nested resources 处理:

#config/routes.rb
resources :images do #-> url.com/images/:id
   resources :comments, only: [:create, :update, :destroy] #-> url.com/images/:image_id/comments
end

#app/controllers/images_controller.rb
class ImagesController < ApplicationController
   def show
      @image = Image.find params[:id]
      @comment = @image.comments.new
   end
end

#app/controllers/comments_controller.rb
class CommentsController < ApplicationController 
   def create
      @image = Image.find params[:image_id]
      @comment = @image.comments.new comment_params
      redirect_to @image if @comment.save
   end

   private

   def comment_params
      params.require(:comment).permit(:body).merge(user_id: current_user.id)
   end
end

您将能够显示如下视图:

#app/views/images/show.html.erb
<%= @image.attribute %>
<%= form_for [@image, @comment] do |f| %>
   <%= f.text_field :body %>
   <%= f.submit %>
<% end %>

当然,您可以将其放入partial。有很多方法可以让它工作,以上只是我处理它的方式。