如何使用另一个对象的id调用对象的create方法?

我正在尝试建立一个具有评论function的画廊。 考虑有3个类:专辑,照片,评论。 这些对象的关系是Album有很多照片,Photo有很多评论。

每个注释都由注册用户保留,因此在注释对象中有comment_text,user_id和photo_id(参考注释所属的照片)。

我想在每张照片的“show”视图下创建一个评论表单。 这是一些Controller和Show视图:

控制器/ photos_controller.rb

class PhotosController < ApplicationController ... def show @photo = Photo.find(params[:id]) @new_comment = @photo.comments.build if user_signed_in? @comment_items = @photo.comments.paginate(page: params[:page]) end ... end 

意见/照片/ show.html.erb

 ...  

所以问题是当我编写CommentsController时,我不知道如何将照片的id(photo_id)从之前的“show”页面传递给create方法。 是否只有通过表格中的隐藏字段传递它? 在Rails中有更优雅的方式吗? 另外,关于安全问题,如果我通过隐藏字段检索photo_id,是否有人能够编写特定的“post”请求,以便将评论发布到相册中的所有照片? (就像很久以前在php论坛中的垃圾邮件发送者…)

感谢您阅读本文,并提前感谢您的回答!

看一下嵌套资源上的rails指南http://guides.rubyonrails.org/routing.html#nested-resources

你的路线会有这样的东西。

 resources :photos do resources :comments end 

你的照片控制器将保持不变,但你的评论控制器需要从url查找照片

 class CommentsController < ApplicationController before_action :get_photo def create @photo.comments.create(params.require(:comment).permit(:comment_text)) .... end ... def get_photo @photo = Photo.find(params[:photo_id]) end end 

和照片视图会有

 <%= form_for [@photo,Comment.new], html: {method: :post} do |c| %> 
<%= image_tag current_user.avatar.url(:thumb) %>

<%= c.label "Enter your comment here:" %>

<%= c.text_area :comment_text %>

<%= c.submit "Submit Comment", class: "btn btn-tiny" %>

<% end %>

应该调用new_photo_comment_path

至于user_id,我只是从user_signed_in帮助器中抓取它。 由于您已经登录,因此无法从Web传递它。