首先,这是我的模特:
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) %>
它工作得很好,并在下拉列表中显示所有用户的电子邮件。但我要显示的是下拉列表中的用户full_name,它是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) %>
答案 0 :(得分:4)
使用以下
<%= collection_select(:event, :user_id, User.all, :id, :full_name) %>
但您必须在用户模型上声明full_name
方法。
# user.rb
def full_name
user_details.full_name
end
或者您可以使用委托
delegate :full_name, to: :user_details
答案 1 :(得分:-1)
尝试:
<%= link_to "#{user.user_details.full_name}", "mailto:#{email}" %>
在你看来,让我知道你是如何继续...
修改强> 在user.rb文件中定义一个返回user_details.full_name的帮助器方法并使用它:
<%= collection_select(:event, :user_id, User.all, :id, :*method_returning_user_details.full_name* %>
答案 2 :(得分:-2)
尝试:
在你看来这
更新:
<% @fullname = User_details.fullname %>
并在您的collection_select
中 <%= collection_select(:event, :user_id, User.all, :id, @fullname) %>
并告诉我进展情况。