【问题标题】:How do I use collection_select?如何使用 collection_select?
【发布时间】:2012-12-09 08:08:30
【问题描述】:

我想使用collection_select,我做了一些研究,让它显示带有正确对象集合的下拉菜单,我可以选择我选择的特定对象。但是从那里我不知道如何通过它。

这是我的代码:

    <%= collection_select :course, :course_id, Course.all, :id, :name, :prompt => "Select a Course:" %>
    <%= link_to 'New Grade', new_grade_path(:course => :course_id ) %>

这是将其传递给控制器​​中的“新”方法的正确方法吗?

如果我在控制器中,这是检索该对象的正确代码吗?

    @course = Course.find(params[:course])

另外,如果我要在视图“new.html.erb”中显示这个,我会使用这个代码吗?

    <%= @course.name %>

编辑:

我认为包含我的关联可能会有所帮助:

  class Grade < ActiveRecord::Base
    belongs_to :course
    belongs_to :task
    belongs_to :student
  end       

  class Course < ActiveRecord::Base
    has_many :students, :dependent => :destroy
    has_many :grades
    has_many :tasks, :through => :grade
    has_many :teams
  end

  class Task < ActiveRecord::Base
    belongs_to :course
    has_many :grades
    has_many :categories
    has_one :eval
  end

我想做的是在 views/grades/index.html.erb 页面中创建下拉菜单,以便用户可以在该课程中选择课程和任务,因此当用户单击“输入新成绩”时',它会将用户在下拉菜单中选择的那些参数传递给views/grades/new.html.erb,这样我就可以做一些事情,比如显示课程名称和我试图上传成绩的任务链接到“输入新成绩”的 new.html.erb 表单。

【问题讨论】:

  • 我认为您的问题的标题具有误导性,除非我遗漏了什么,否则您似乎并不是在问如何使用collection_select。虽然很难说出您的要求。

标签: ruby-on-rails ruby activerecord views controllers


【解决方案1】:

您应该在视图页面上创建表单以将参数传递给控制器​​。

views/grades/index.html.erb

<%= form_tag(new_grade_path, method: 'get') do %>
  <%= label_tag "Courses" %>
  <%= select_tag(
    :choose_course,
    options_from_collection_for_select(Course.all, "id", "name")
  ) %>
  <%= submit_tag "Choose course" %>
<% end -%>

controllers/grades_controller.rb

def new
  @course  = Course.find(params[:choose_course])
end

然后在 views/grades/new.html.erb 中可以使用@course.name 显示用户在上一页选择的课程。

【讨论】:

  • 我认为这不适合我的情况。我想在我的索引视图中选择一门课程,这样当我进入我的新视图时,我可以使用该课程对象来显示课程中的学生。然后我就可以上传课程中所有学生的成绩@alex
  • 我不明白你的意思,Ejay。试着再解释一遍。
  • 抱歉,我已经为您更新了问题。我希望这有助于更好地理解我的问题。谢谢你。 @亚历克斯
  • 知道了,查看修改后的答案
猜你喜欢
  • 2011-05-12
  • 2016-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 2013-03-29
  • 1970-01-01
  • 2015-05-07
相关资源
最近更新 更多