【问题标题】:Ruby on Rails how to use submit button with radio buttonsRuby on Rails 如何使用带有单选按钮的提交按钮
【发布时间】:2015-05-20 17:00:13
【问题描述】:

对于我的期末项目,我需要创建两个带有提交按钮的单选按钮,用于显示我所有课程和专业课程的 GPA。我可以轻松地显示它们,但是当我需要使用单选按钮只显示一个时会卡住

<h2>Please select which GPA you would like to view:</h2>

<%= form_tag("/trans/transcript", :method => "get") do %>
<table>
  <tr>
    
	<th>Major Credits</th>
	<th>All Credits</th>
  </tr>
  <tr>
    
	<td><%= radio_button_tag(:gpa, "Major") %></td>
	<td><%= radio_button_tag(:gpa, "All") %> </td>
  </tr>
  
  
</table>
  <%= submit_tag("View GPA") %>
<% end %>



<p> Major credits GPA  <%= @transcript.GPA_for_major %>
<p> All credits GPA  <%= @transcript.GPA_for_non_major %>

一切看起来都很好,但我不知道如何设置控制器来说明他是否点击了主要 gpa 单选按钮并点击了“查看 GPA”,这 应该显示

【问题讨论】:

  • 你想在同一个视图中显示 GPA 吗?
  • 是的,在同一个视图中是我的课程,所以在它下面是单选按钮所在的位置

标签: ruby-on-rails ruby button submit radio


【解决方案1】:

简短回答

  • 在 TransController 的脚本操作中创建一个实例变量 @gpa
  • 在转录操作中,检查参数[:gpa]
    • 如果 params[:gpa].nil 将 @gpa 和 @transcript 设置为 nil?
    • 如果 params[:gpa] 不为零,则将 @gpa 设置为 params[:gpa] 和 @transcript
  • 在视图/trans/transcript.html.erb
    • 如果 @gpa 为 nil,则不显示任何内容
    • 如果 @gpa == "Major" 显示 @transcript.GPA_for_major
    • 如果 @gpa == "All" 显示 @transcript.GPA_for_non_major

长答案

假设控制器是trans,action是transcript,下面是你在TransController中应该做的事情

class TransController < ApplicationController

  def transcript
    if params[:gpa].nil?
      @transcript = @gpa = nil
    else
      @gpa = params[:gpa]
      @transcript = ... # Find your transcript here
    end
  end
  # ... other actions
  # ... other actions
  # ... other actions
end

下面是 trans/transcript.html.erb 视图的外观 -

<h2>Please select which GPA you would like to view:</h2>
<%= form_tag('trans/transcript', :method => "get") do %>
  <table>
    <tr>
      <th>Major Credits</th>
      <th>All Credits</th>
    </tr>
    <tr>
      <td>Major<%= radio_button_tag(:gpa, "Major") %></td>
      <td>All<%= radio_button_tag(:gpa, "All") %> </td>
    </tr>
  </table>
  <%= submit_tag("View GPA") %>
<% end %>

<% if @gpa == "Major" %>
  <%= @transcript.GPA_for_major %>
<% elsif @gpa == "All" %>
  <%= @transcript.GPA_for_major %>
<% end %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多