select_tag rails,仅显示特定列表

时间:2013-04-01 03:15:56

标签: ruby-on-rails ruby-on-rails-3 forms html-select

我有公司的这个模型

class Company < ActiveRecord::Base
   attr_accessible :description, :name, :type
   belongs_to :type, :class_name => "CompanyType", :foreign_key => :company_type_id
end

这个公司类型的模型

class CompanyType < ActiveRecord::Base
  attr_accessible :name
end

然后在另一个_form文件中我想创建一个select,它只显示公司类型为“Financial”的公司列表。如果该公司的类型是“油”,则不要在下拉列表中显示它。

如何将其插入此select_tag代码并更改模型?

<%= select_tag :company, 
    options_from_collection_for_select(Company.order(:name), "id", "name"),
    :include_blank => true%>

1 个答案:

答案 0 :(得分:3)

<%= select_tag :company, 
options_from_collection_for_select(Company.where(:type => "Financial").order(:name), "id", "name"),
:include_blank => true%>

基本上只需添加.where(:type =&gt;“Financial”),就可以在其中添加一个简单的.where语句。虽然您可能想要删除

Company.where(:type => "Financial").order(:name)

到您的控制器并将其保存在像

这样的实例变量中
@companies = Company.where(:type => "Financial").order(:name)

并且视图逻辑看起来像这样。

<%= select_tag :company, 
options_from_collection_for_select(@companies, "id", "name"),
:include_blank => true%>

编辑更新的问题

模型

class CompanyType < ActiveRecord::Base
  has_many :companies
  attr_accessible :name
end

控制器

@companies = CompanyType.where(:name => "Financial").companies.order(:name)

并且视图逻辑看起来像这样。

<%= select_tag :company, 
options_from_collection_for_select(@companies, "id", "name"),
:include_blank => true%>