Search code examples
ruby-on-railsrubyactiverecordviewcontrollers

How do I use collection_select?


I want to use collection_select, and I've done some research to get it to display the drop down menu with the right Collection of objects and I get to choose a specific object of my choice. But from there I don't know how to pass it.

This is my code:

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

Is this the right way to pass it to the 'new' method in the controller?

And if I'm in the controller, is this the correct code to retrieve that object?

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

Also, if I was to display this in the view 'new.html.erb', would I use this code?

    <%= @course.name %>

EDIT:

I thought it might help to include my associations:

  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

What I wanted to do was to create drop down menus in the views/grades/index.html.erb page so that the user could pick a course and a task in that course, so when the user clicks 'input new grades', it'll pass those parameters that the user picked in the drop down menu to views/grades/new.html.erb so that I can do things like display the course's name and the task I'm trying to upload grades for in the new.html.erb form that's linked to 'input new grades'.


Solution

  • You should create form on view page to pass params to the controller.

    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
    

    Then in views/grades/new.html.erb you can use @course.name to show the course that user has choose on the previous page.