Rails 3中的嵌套资源出错

时间:2012-06-13 07:26:51

标签: ruby-on-rails

我的routes.rb

resources :post do
      resources :answers do
        resources :anscomments
      end
    end

模型

post.rb

has_many :answers

answer.rb

belongs_to :post
has_many :anscomments

anscomment.rb

belongs_to :answer

控制器

answers_controller.rb

class AnswersController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @answer = @post.answers.create(params[:answer])
    redirect_to post_path(@post)
  end
end

anscomments_controller.rb

class AnscommentsController < ApplicationController
  def create
    @answer = Answer.find(params[:answer_id])
    @anscomment = @answer.anscomments.create(params[:anscomment])
    redirect_to post_path(@answer)
  end
end

视图

查看/后/ show.html.erb

<table align=center width="60%" bordercolor="black">

    <tr>
        <td align="center">
            <h2>
                <%=@post.title%> 
            </h2>
        </td>
    </tr>
    <tr>
        <td align="center">
            <h3><%=@post.body%></h3>
        </td>
    </tr>
    <tr>
        <td align="center">
            This Post comes under:<%=@post.tag%>
        </td>
    </tr>

</table>
<br />
<h2 align="center">Answers</h2>
<div align="center">
    <% @post.answers.each do |answer| %>
    <table width="50%" border="1">
        <tr>
            <td align="center">
                <%= answer.body %>
            </td>
        </tr>



        <div align="center">
            <% @answer.anscomments.each do |anscomment| %>
            <table width="40%" %>
                <tr>
                    <td>
                        <%= anscomment.body %>
                    </td>
                </tr>
            </table>
            <%end%>
        </div>
        <div align="center">
            <%= form_for([@answer,@answer.anscomments.build]) do |f| %>
            <table>
                <tr>
                    <td><%= f.text_area :body %></td>
                </tr>
                <tr>
                    <td><%= f.submit "Submit Comment" %></td>
                </tr>
            </table>
            <%end%>
        </div>



    </table>
    <% end %>
</div>
<br />
<h2 align="center">Your Answer</h2>
<div align="center">
    <%= form_for([@post, @post.answers.build]) do |f| %>
    <table>
        <tr>
            <td><%= f.text_area :body %></td>
        </tr>
        <tr>
            <td><%= f.submit "Post Your Answer" %></td>
        </tr>
    </table>
    <% end %>
</div>

当我试图点击个别帖子时,我收到的错误就像----“nil的未定义方法`anscomments':NilClass”

请找到解决方案.....

1 个答案:

答案 0 :(得分:0)

尝试在answer.anything

中使用@answer.anything代替post/show.html.erb
<%= answer.body %>

是对的,

<% @answer.anscomments.each do |anscomment| %>

错误,@ answer未初始化(无)