目前我正在使用’form_for’并传入current_user.单击提交时,它将指向User / show操作.我想转到详细说明用户结果的页面.我该怎么做呢?
这是我的(非常粗略的测试)形式,到目前为止,一个多项选择问题(由引导程序设计):
<%= form_for([current_user]) do |f| %> <p> <%= text_field(:user, :name) %> </p> <div class="btn-group-vertical clearfix form-group" data-toggle="buttons"> <label class="btn btn-primary text-left"> <input name="options" id="option1" type="radio" onclick="multiChoiceClick(1, 1)">A. Always. I'm the leader and should have the final say </label> <label class="btn btn-primary text-left"> <input name="options" id="option2" type="radio">B. Sometimes, but I think the group should make decisions if possible </label> <label class="btn btn-primary text-left"> <input name="options" id="option3" type="radio">C. I generally don't get involved. The group can make their own decisions without my help </label> </div> <p> <%= f.submit("Get my results!") %> </p> <% end %>
我目前正在将text_field包含在用户名中作为测试.
我想知道如何将第一个多项选择问题“连线”给用户,但在点击“获取我的结果”时显示结果页面.
我可能在这段代码中有几个错误.如果我这样做,并且你有答案,请你指出我的错误并解释做正确的方法吗?很抱歉这么具体,但我之前有过一些评论只能指出什么是错的,没有别的选择.
谢谢.
编辑:
有人要求控制器,所以这里是:
class HomeController < ApplicationController def index end def whattypeofleader @user = current_user #@quiz_answer = current_user.quiz_answers(0).build end def post_params params.require(:quiz_answer).permit(:body, :user_id) end end
我已将@quiz_answer注释掉,因为我不确定如何将其与表单相关联.在用户控制器中,用户has_many:quiz_answers和QuizAnswer belongs_to:user
重定向应该来自您的控制器.管理数据后,一个简单的:
redirect_to results_path
您的结果路径应该在config / routes.rb中.
不要犹豫与控制器分享更多一点,看看我们是否可以更深入:)
[编辑]在评论之后
免责声明:不确定Rails的测验复数管理……
您的表单应该由新方法呈现,如下所示:
class QuizzesController < ApplicationController ... def new @user = current_user #you now have access to the @user variable in your view end ... def create # do your thing with your params # usually, you want to redirect to the results page if the action has been saved # so let's say that you built an @object beforehand with the params you received # extactly like @DarkMousse answer : if @object.save redirect_to results_path flash[:notice] = "Thanks for submitting these questions" else render 'new' end # this way, if all is good, go to results_path, else, return to the 'new' end ... end
要访问此操作,您必须有一个到达它的路由,让我们转到config / routes.rb
YouApplicationName::Application.routes.draw do ... #it 'opens' the routes to access all method from your quizzes controller resources :quizzes resources :results ... end
现在您可以访问测验/新.它将在views / quizzes / new中呈现视图,您可以在其中使用如下形式:
form_for @user do |f| # ... your form ... end
请注意,由于我们的QuizzesController中的新方法,@ user是可访问的.
现在我们在路由中添加了一个结果,在终端中有一个rake路由,你应该找到一个results_path导致你的(尚未创建:))ResultsController索引方法.
它可能看起来像这样:
class ResultsController < ApplicationController def index # in order to access all the results in our view @results = Results.all end end
这样,results_path将导致此操作,默认情况下(感谢rails)调用views / results / index.html.erb进行渲染.