如何创建一个问题列表,其中answer_form将出现在每个question_partial中?

时间:2015-01-24 21:28:42

标签: ruby-on-rails view routes router partial

我想创建一个网页,在那里我可以看到包含问题列表的项目。

"项目/ 1 /问题"

在routes.rb中我有

resources :items do 
 resources :questions
end

问题/ index.html.erb

<div class="panel panel-default">
  <div class="panel-heading">
    <td><%= @item.title %></td>
  </div>
  <div class="panel-body">
    <p><%= @item.description %></p>
    <p><%= @item.price %></p>
    </div>
</div>  

  <div class="panel-body"><%= render 'questions/form' %></div>


  <div class="panel-body">
    <% if @item.questions.any? %>
    <%= render partial: 'questions/question', collection: @item.questions %>       </div>
    <% end %>
  </div>

问题/ _question.html.erb

<p><%= question.body %></p>

现在我想为admin创建一个答案选项,看起来像每个question_partial中的答案字段。

所以我创建了一个模型答案,belongs_to :question(问题模型has_one :answer),question_id:integer, body:string

在answers_controller.rb中 ...

def new
  @answer = Answer.new(answer_params)
end

def create
  @question = Question.find(params[:question_id])
    @answer = @question.build_answer(answer_params)
    if @current_user == @admin
      @answer.save
      flash[:success] = "Your answer has been sent!"
      redirect_to item_questions_path(@item)
    else
      flash[:errors] = "Your answer hasn't been sent!"
      redirect_to item_question_path(@item)
    end
end

def show
  @answer = Answer.find(params[:id])
end

并尝试创建form_for @ question.answer

问题/ _question.html.erb

<p><%= question.body %></p>
<% if @current_user = @admin %>
 <%= form_for Answer.new do |f| %>
  <p>
    <%= f.text_field :body" %>
  </p>
  <p>
    <%= f.submit "answer"%>
  </p>
 <% end %>
<% end %>

并得到错误&#34;未定义的方法`answers_path&#39;&#34;

我想使用问题列表构建item_page,其中每个question_partial应该包含:answer或answer_form(所有在一个页面上,&#39; items /:id / questions&#39;)

我认为我在路由器中有问题(也许在answers_controller中), 但不知道它是如何组织起来的。

你知道吗?) TY

2 个答案:

答案 0 :(得分:0)

您收到错误undefined method 'answers_path',因为您没有获得答案create操作(或任何答案操作)的路径。将resources :answers添加到您的其他路线下的路线文件中。

答案 1 :(得分:0)

您需要根据嵌套资源的方法定义答案的路线,如下所示:

的routes.rb

resources :items do 
 resources :questions do
   resource :answer
 end
end

网址现在看起来像/items/:item_id/questions/:question_id/answer,这意味着网址中没有答案ID,因为它是一个单一的资源,即一个问题只能有一个答案。您还必须调整控制器以首先获取问题,然后访问答案,如@question.answer

answers_controller.rb

def new
  # first find the question, then build an answer for it
  @question = Question.find(params[:question_id])
  @answer   = @question.build_answer
end

def show
  @question = Question.find(params[:question_id]) 
  # NOTE: @answer can be nil here if no answer has been created
  @answer   = @question.answer
end

在您的视图中,您有另一个拼写错误,您使用赋值运算符=进行比较。我还更改了form_for帮助程序以构建正确的URL。

问题/ _question.html.erb

<p><%= question.body %></p>
<% if @current_user == @admin %>
 <%= form_for [question.item, question, question.answer.present? ? question.answer : question.build_answer] do |f| %>
  <p>
    <%= f.text_field :body" %>
  </p>
  <p>
    <%= f.submit "answer"%>
  </p>
 <% end %>
<% end %>