正确的方法是为现有视图轨添加注释

时间:2016-01-28 09:32:59

标签: ruby-on-rails ruby model-view-controller comments

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

1 个答案:

答案 0 :(得分:2)

这通常由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。有很多方法可以让它发挥作用,上面就是我处理它的方式。