Rails 3 build a select tag with has_many belongs_to association

戏子无情 提交于 2019-12-21 08:37:59

问题


Based on following models

class Company < ActiveRecord::Base
  belongs_to :country
end

class Country < ActiveRecord::Base
  has_many :companies
end

I want to have in my companies/_form a select tag containing all the countries

I think that the Company.new(params[:company]) in companies_controller#create can create the association between company and the selected country

I'm running rails 3.0.0, what is the best way to achieve that?

thanks for your insights


回答1:


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.



来源:https://stackoverflow.com/questions/3763963/rails-3-build-a-select-tag-with-has-many-belongs-to-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!