Rails 3中建立一个选择标记与的has_many belongs_to的关联 [英] Rails 3 build a select tag with has_many belongs_to association

查看:166
本文介绍了Rails 3中建立一个选择标记与的has_many belongs_to的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据以下型号

class Company < ActiveRecord::Base
  belongs_to :country
end

class Country < ActiveRecord::Base
  has_many :companies
end

我想在我的公司/ _form包含所有国家的一个选择标记

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

我觉得 Company.new(PARAMS [:公司]) companies_controller#创建可以创建公司和选定的国家之间的关联

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

我跑铁轨3.0.0,什么是实现这一目标的最佳途径?

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

感谢您的见解。

推荐答案

collection_select 应该为你做的伎俩:

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

以上code假定国家表有一个名称列。如果不是这样,更换第五个参数与任何国家名称的列是

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.

查找在<获得更多的信息href=\"http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select\">Rails API文档。

这篇关于Rails 3中建立一个选择标记与的has_many belongs_to的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆