Search code examples
ruby-on-railsruby-on-rails-4collection-select

add to collection_select dynamically


I have 3 Models: Course, Unit and Plan. relations are like:

Course has_many units
Unit belongs_to course

Plan has_and_belongs_to_many units
Unit has_and_belongs_to_many plans

In the create_plan page, I have a collection_select to get units of my plan; but units don't have title,they use their course title. I want to show the course title in the collection_select. how can I do that?


Solution

  • Delegate title to the course

    class Unit
      belongs_to course
      delegate :title, to: :course
    end
    
    <%= f.collection_select(:unit_id, Unit.all, :id, :title, prompt: true) %>