Ruby on rails 在Rails中使用collection_select时如何显示相关模型的属性
我设置了一个MTI,客户机继承自Person。我也有一个项目,这是在一对一的关系与客户模型。在我的视图project/new.html.erb中,我想创建一个下拉菜单,其中包含可供选择的客户端名称Ruby on rails 在Rails中使用collection_select时如何显示相关模型的属性,ruby-on-rails,ruby,Ruby On Rails,Ruby,我设置了一个MTI,客户机继承自Person。我也有一个项目,这是在一对一的关系与客户模型。在我的视图project/new.html.erb中,我想创建一个下拉菜单,其中包含可供选择的客户端名称 <%= f.collection_select(:client_id, Client.all, :id, :XXX, {include_blank: true, :data => {:placeholder => "Select a client"}}, {:class =>
<%= f.collection_select(:client_id, Client.all, :id, :XXX, {include_blank: true, :data => {:placeholder => "Select a client"}}, {:class => "chosen-select", :tabindex => "-1", :style => "width:350px;", }) %>
{:placeholder=>“选择客户端”},{:class=>“选择的客户端”,:tabindex=>“-1”,:style=>“宽度:350px;”,})%>
XXX通常是一个符号,表示直接模型(在本例中为客户机)的属性。如何显示实际上是Person类属性的name属性 更新 我在客户端类中添加了一个person\u name方法
class Client < ActiveRecord::Base
has_many :projects
has_one :person, as: :profile, dependent: :destroy
attr_accessible :person_attributes, :pref_hours_of_contact, :pref_method_of_contact
accepts_nested_attributes_for :person
def person_name
person.name
end
end
class客户端
我亦修正了以下意见:
<%= f.collection_select(:client_id, Client.all, :id, :person_name, {include_blank: true, :data => {:placeholder => "Select client"}}, {:class => "chosen-select", :tabindex => "-1", :style => "width:350px;", }) %>
{:placeholder=>“选择客户端”},{:class=>“选择的客户端”,:tabindex=>“-1”,:style=>“宽度:350px;”,})%>
我还没有尝试过,但我相信您可以在客户机类中使用一个方法来输出Person属性。我假设您想要获得一个人名:
请注意在for集合中选择的内容:
:value\u方法和:text\u方法参数是要调用的方法
在集合的每个成员上
因此,如果您可以向将检索Person属性的客户机对象发送一个方法,那么就可以开始了。这实际上取决于您如何定义MTI,但归根结底,您的客户机类中始终可以有以下内容:
def person_name
# Access your super attribute
end
所以你可以做:
<%= f.collection_select(:client_id, Client.all, :id, :person_name, {include_blank: true, :data => {:placeholder => "Select a client"}}, {:class => "chosen-select", :tabindex => "-1", :style => "width:350px;", }) %>
<%= f.collection_select(:client_id, Client.all, :id, :name, {include_blank: true, :data => {:placeholder => "Select a client"}}, {:class => "chosen-select", :tabindex => "-1", :style => "width:350px;", }) %>