【发布时间】:2015-11-04 05:07:26
【问题描述】:
我想实现 current_user 回答问题的功能。为了实现它,我需要将 question_id 数据从视图传递到控制器。 特别是,
1) 将views/homes/popular.html.erb中的question_id传递给answers_controller.rb
2) 将 question_id 从 answers_controller.rb 传递到 views/answers/new.html.erb
3) 将问题 ID 从 views/answers/new.html.erb 传递到 answers_controller.rb
我想将 question_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 = params [:question_id] 和answer/new.html使用隐藏字段f.hidden_field :@question发送数据。 -
亲爱的 Pardeep 通过使用 f.hidden_field,我明白了!谢谢!
-
太好了!!很高兴为您提供帮助。
标签: ruby-on-rails ruby view controller