[英]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_path
是method_controller_path
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.