将数据从嵌套资源调用到rails app中的主资源

时间:2013-07-14 09:00:53

标签: ruby-on-rails ruby-on-rails-3 activerecord rails-activerecord nested-resources

我有一个支持Rails的博客应用程序。我有PostsComments个表格。两者都与has many - belongs to关系相关联,资源也嵌套在config/routes.rb中。在我的posts#show中,我想打电话给与帖子相关的评论。我写过如下代码。但是我遇到了一些像Couldn't find Comment without an ID这样的错误。以下是与此问题相关的代码:

# app/controllers/posts_controller.rb
def show
    @post = Post.find(params[:id])
    @comments = Comment.find(params[:post_id])

    respond_to do |format|
        format.html # show.html.erb
        format.json { render json: @post }
    end
end


# app/views/posts/show.html.erb
<h3><%= @post.title.titleize %></h3>
<p><%= @post.content %></p>
<% if @comments %>
    <% @comments.each do |com| %>
        <h4><%= com.title.titleize %></h4>
        <p><%= com.content %></p>
        <hr />
    <% end %>
<% else %>
    <p>No Comments Found , <%= link_to 'Add One?', new_post_comment_path(@post) %></p>
<% end %>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>


# config/routes.rb
    resources :posts do
      resources :comments
    end

编辑:

现在我在includes(:comments)中使用了posts_controller.rb

# app/controllers/posts_controller.rb
def show
    @post = Post.includes(:comments).find(params[:id])
    #@comments = Comment.find(params[:post_id])

    respond_to do |format|
        format.html # show.html.erb
        format.json { render json: @post }
    end
end

我也分别更新了show.html.erb

<h3><%= @post.title.titleize %></h3>
<p><%= @post.content %></p>

<% if @post.comments %>
    <% @post.comments.each do |com| %>
    <h4><%= com.title.titleize %></h4>
    <p><%= com.content %></p>
    <hr />
<% end %>
<% else %>
    <p>No Comments Found , <%= link_to 'Add One?', new_post_comment_path(@post) %></p>
<% end %>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

这是新的错误: PG::Error: ERROR: column comments.commentable_type does not exist LINE 1: SELECT "comments".* FROM "comments" WHERE "comments"."comme... ^ : SELECT "comments".* FROM "comments" WHERE "comments"."commentable_type" = 'Post' A...

0 个答案:

没有答案