控制器我想具體化是CURRENT_USER回答一個問題的功能。爲了實現它,我需要將question_id數據從視圖傳遞給控制器。 特別地,如何通過從視圖中的數據,以在軌
1)從視圖/舍/ popular.html.erb傳遞question_id到answers_controller.rb
2)從answers_controller.rb傳遞question_id到意見/答案/ new.html.erb
3)將answers_id從views/answers/new.html.erb傳遞給answers_controller.rb
我想將answers_id傳遞給answers_controller.rb的hogehoge。你能告訴我該怎麼做嗎?
#app/controllers/homes_controller.rb
class HomesController < ApplicationController
def popular
@questions = Question.all
@questions.each do |question|
@answer = question.answers.highest
end
end
end
#app/views/homes/popular.html.erb
<div class="row">
<div class="row">
<h3>Popular</h3>
<% @questions.each do |question| %>
<li><%= link_to question.body, new_answer_path ,question_id:question.id%></li>
<% end %>
</div>
</div>
#app/controllers/answers_controller.rb
class AnswersController < ApplicationController
def new
@answer = Answer.new
end
def create
@answer = current_user.answers.create(answer_params)
if @answer.save
redirect_to root_url
else
render 'new'
end
end
private
def answer_params
hogehoge
end
end
#app/views/answers/new.html.erb
<%= form_for @answer, :url => answers_path do |f| %>
<div class="page-header">
<h2>Please answer</h2>
</div>
<div class="span6 offset3">
<%= f.label :body %><br>
<%= f.text_field :body %>
</div>
<%= f.submit 'post', class: 'btn btn-primary' %>
<% end %>
要從視圖的數據發送到控制器,你可以使用查詢字符串,你在'popular.html.erb'和答案控制器你習慣在'PARAMS數據[:question_id]',使用實例變量在新的行動@問題=參數[:question_id]和在'答案/ new.html'使用隱藏字段'f.hidden_field:@ question'發送數據。 –
親愛Pardeep 通過期運用f.hidden_field,我知道了!謝謝! – lalala
偉大的!,其我很願意幫助你。 –