Ruby 如何将值从单选按钮传递到控制器方法

问题描述

嗨,我已经在这个问题上困扰了太久了。所以我对 ruby​​ 和 js 没有信心。

当前我需要将基于我从单选按钮单击的值传递给控制器​​,以便我可以比较数据库中的值是否匹配。

这是我的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> 

This shows that my radio buttons have values assigned to them

当我点击提交按钮时,它会转到我的 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...