Rails 3 build a select tag with has_many belongs_to association

前端 未结 1 1673
Happy的楠姐
Happy的楠姐 2021-02-20 09:31

Based on following models

class Company < ActiveRecord::Base
  belongs_to :country
end

class Country < ActiveRecord::Base
  has_many :companies
end


        
相关标签:
1条回答
  • 2021-02-20 10:15

    collection_select should do the trick for you:

    collection_select(:company, :country_id, Country.all, :id, :name, :prompt => 'Please select country')
    

    The above code assumes that the countries table have a name column. If it doesn't, replace the fifth parameter with whatever the column of the country name is.

    :prompt means that you're forcing the user to choose one country.

    Find more information in the Rails API documentation.

    0 讨论(0)
提交回复
热议问题