尝试添加评论部分,获取:无法找到没有ID的帖子

时间:2014-07-12 13:37:52

标签: ruby-on-rails ruby-on-rails-4

我在我的网页上创建了类似新闻源的功能,其中显示了您关注的人创建的所有帖子。就像Facebook一样,我希望用户能够直接从帖子下面的新闻源发表评论。

这可能是一个简单的解决方法,但我无法弄清楚最好的方法,甚至不知道如何获得post_id。

我目前的 newsfeeds / index.html.erb 如下所示:

<ul>
 <% @activities.each do |activity| %>
  <li> <%= image_tag(activity.owner.avatar.url(:thumb), height: "64", width: "64") %>  <%= activity.owner.fullname %>
   <ul>
    <li><strong><%= activity.trackable.title %></strong></li>
    <li><%= activity.trackable.content %></li>
     <ul>
       <li><%= render 'comments/form' %></li>
     </ul>
   </ul>
 </li>
<% end %>
</ul>

comments / _form.html.erb

<%= form_for [@post, @comment] do |f| %>
 <%= f.text_area :content %>
 <%= f.submit "Add comment" %>
<% end %>

然后我们有控制器:

newsfeeds_controller.rb

def index
 @activities = PublicActivity::Activity.order("created_at desc").where(owner_id: current_user.friend_ids, owner_type: "User")
 @comment = Comment.new
end

comments_controller.rb

class CommentsController < ApplicationController
 before_filter :load_post

def create
 @comment = @post.comments.build(params[:comment])
 @comment.user = current_user
 if @comment.save
   @comment.create_activity :create, owner: current_user
   redirect_to @post, notice: "Comment was created."
 else
   render :new
 end
end
....
 def load_post
  @post = Post.find(params[:post_id])
 end
end

所以我的问题是如何修复它以便我存储post_id并找到它?

1 个答案:

答案 0 :(得分:1)

从我所看到的评论表格似乎是对嵌套路线发出请求(即/ posts /:post_id / comments)。然后将从CommentsController中的url检索post_id。

当前的'comments / _form.html.erb'部分要求@post变量能够生成正确的操作URL(在这种情况下,@ post变量似乎不会设置在任何地方)。

要解决此问题,您可以将“post”作为局部变量传递给表单partial。这样你的表单部分就可以创建正确的URL,你的控制器可以访问post_id。

另见http://guides.rubyonrails.org/layouts_and_rendering.html#local-variables

新闻源/ index.html.erb:

<ul>
 <% @activities.each do |activity| %>
 <li> <%= image_tag(activity.owner.avatar.url(:thumb), height: "64", width: "64") %>  <%= activity.owner.fullname %>
   <ul>
    <li><strong><%= activity.trackable.title %></strong></li>
    <li><%= activity.trackable.content %></li>
     <ul>
       <li><%= render 'comments/form', post: activity.trackable %></li>
     </ul>
   </ul>
 </li>
<% end %>
</ul>

评论/ _form.html.erb:

<%= form_for [post, @comment] do |f| %>
 <%= f.text_area :content %>
 <%= f.submit "Add comment" %>
<% end %>

(可能有更简洁的方法来实现这一点)

要添加嵌套路线,请编辑'config / routes.rb'

resources :posts do
  resources :comments
end

PS: 在同一页面上多次呈现相同的表单时,所有表单及其输入字段的DOM ID都是相同的。为避免这种情况,您应该在form_for调用中设置namespace-option(请参阅此问题:Rails: Using form_for multiple times (DOM ids)

评论/ _form.html.erb:

<%= form_for [post, @comment], namespace: post.id do |f| %>
 <%= f.text_area :content %>
 <%= f.submit "Add comment" %>
<% end %>