首先,这是我的模型:
class User < ActiveRecord::Base
has_one :event
has_one :user_details, :dependent => :destroy
accepts_nested_attributes_for :user_details, :event
end
class UserDetails < ActiveRecord::Base
belongs_to :user
def full_name
[self.first_name, self.last_name].compact.join(' ')
end
end
class Event < ActiveRecord::Base
belongs_to :user
end
我的观点之一是这条线
<%= collection_select(:event, :user_id, User.all, :id, :email) %>
它工作得很好,并在下拉列表中显示所有用户的电子邮件。但我要显示的是下拉列表中的用户全名,它是 user_details 模型的一部分。
我怎样才能做到这一点?
# basically i need to change :email to something like :user_details.full_name, but i'm not sure how.
<%= collection_select(:event, :user_id, User.all, :id, :email) %>
编辑
我试过了:
# undefined method `full_name' for :user_details:Symbol
<%= collection_select(:event, :user_id, User.all, :id, :user_details.full_name) %>
# This shows the dropdown with a bunch of UserDetails objects aka #<UserDetails:asfjoisdfa>
<%= collection_select(:event, :user_id, User.all, :id, :user_details) %>
# undefined method `full_name' for #<User:0x007ff18bf0c470>
<%= collection_select(:event, :user_id, User.all, :id, :full_name) %>