繁体   English   中英

Ruby 如何将值从单选按钮传递到 Controller 方法

[英]Ruby How To Pass Values From Radio Button To Controller Method

嗨,我解决这个问题的时间太长了。 所以我对 ruby 和 js 没有信心。

目前我需要根据我从单选按钮单击的内容将值传递到 controller 中,这样我就可以比较数据库中的值是否匹配。

这是我的show.html.erb

<h1>Questions</h1>
      <%= @questions.question %>

<div class="container mt-sm-5 my-1">
    <div class="question ml-sm-5 pl-sm-5 pt-2">
        <div class="py-2 h5"><b></b></div>
        <div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3" id="options"> 
        <% str = @questions.answers.to_s %>
        <% pairs = str.split(',').map { |pair| pair.split('=>') }%>
        <% pairs.each do |sub_array| %>
    #this is the part where it prints out what is in my db and also sets the value corresponding to the click
             <label class="options"> <%= sub_array[1] if sub_array[1] != "nil" %><input type="radio" name="radio" value=<%= sub_array[0] if sub_array[0] != "nil" %>> <span class="checkmark"></span> </label> 
             <% end %>
        
    </div>
    
    <div class="d-flex align-items-center pt-3">
        <!--<div id="prev"> <button class="btn btn-primary">Previous</button> </div>-->
        <!--<div class="ml-auto mr-sm-5"> <button class="btn btn-success" onclick="window.location='quiz#index'">Next</button></div>-->
        <%= link_to_remote 'Submit now', :url => {:action=>"do"}, :submit => "radio_buttons"%>
        </div>
</div> 

这表明我的单选按钮已分配给它们的值

当我点击提交按钮时,它会转到我的 quiz_controller.rb 但问题是它运行我的 show 方法而不是我的 do 方法? 我不知道如何实现我的 do 方法来接收参数以进行比较

class QuizController < ApplicationController
    
    def show
        @questions = Question.find(params[:format])
    end
    
    def show_url
        
        redirect_back(fallback_location: root_path)
    end
    
    def index
        @questions = Question.all
        Question.logic
    end
    
    def do
        
    end 
    
    
private

    
end 


routes.rb

Rails.application.routes.draw do
  root to: 'home_page#index' 
  
  get 'show_url/:id', to: 'quiz#show'
  get    '/show', to: 'quiz#show'
  get    '/quiz',  to: 'quiz#index'
end

基于点击的index.html.erb会传入id进行展示

<h2>Questions</h2>

<table>
  <tr>
    <th>Question</th>
    <th>Button</th>
  </tr>
 </tr>
   <% @questions.each do |q| %>
  <tr>
    <td><%= q.question %></td>
    <td><%= link_to 'Question', show_url(q.id), method: :get %></td>
    <td><%= q.id %> Button</td>
    <% end %>
  </tr>
</table>

</body>
</html>

提前谢谢你!

我会在这里查看这个关于如何从视图中的按钮调用特定方法的答案: How to call a controller method from a button in rails 4

您可以通过调用向按钮添加method_controller_path来明确设置您希望按钮调用的方法。

IE: <%= button_to 'Invite a user', new_project_invite_path, method: :get, remote: true, class: 'btn primary' %>其中new_project_invite_pathmethod_controller_path

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM