0

我的路线.rb

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

楷模

post.rb

has_many :answers

答案.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:NilClass 的未定义方法`anscomments'”

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

4

1 回答 1

0

尝试使用answer.anything而不是@answer.anythinginpost/show.html.erb

<%= answer.body %>

是正确的,

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

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

于 2012-06-13T07:40:36.113 回答