2014-07-11 157 views
2

我有一个拥有多个帐户的用户。我想使用一个collection_select来让用户选择他想使用的帐号。 select需要在user_accounts表中分配给用户的所有帐户中进行选择,但select需要检查帐户表以获取下拉菜单需要显示的帐户的名称。Rails Collection_Select Has_Many通过

#user.rb 
class Account < ActiveRecord::Base 
    cattr_accessor :current_id 

    belongs_to :owner, class_name: 'User' 
    has_many :user_accounts 
    has_many :users, through: :user_accounts 

    accepts_nested_attributes_for :owner  

end 

#user.rb 
class User < ActiveRecord::Base 
    has_one :owned_account, class_name: 'Account', foreign_key: 'owner_id' 
    has_many :user_accounts 
    has_many :accounts, through: :user_accounts 
end 

#user_account.rb 
class UserAccount < ActiveRecord::Base 
    belongs_to :account 
    belongs_to :user 
end 

如果我用下面,选择的作品,但只显示ACCOUNT_ID:

#settings.html.erb 
<%= form_tag change_account_path do %> 
    <%= collection_select :user_account, :id, current_user.user_accounts, :id, :id %> 
    <%= submit_tag "Sign in", class: "btn btn-large btn-primary" %> 
<% end %> 

我试图取代collection_select:

<%= collection_select :user_account, :id, current_user.user_accounts, :id, :name %> 

返回以下错误:

undefined method `name' for #<UserAccount id: 1, account_id: 27, user_id: 55> 

我试图通过地图功能结合2个表,但也没有成功:

#settings.html.erb 
<%= form_tag change_account_path do %> 
    <%= collection_select :user_account, :id, current_user.user_accounts.map{|x| {:id => x.account_id, :name => x.account.name} }, :id, :name %> 
    <%= submit_tag "Sign in", class: "btn btn-large btn-primary" %> 
<% end %> 

此选项给了我以下错误:

undefined method `name' for {:id=>27, :name=>"S1"}:Hash 

回答

1

您可以使用OpenStruct此:

current_user.user_accounts.map { |x| OpenStruct.new(:id => x.account_id, :name => x.account.name) } 

但可能你应该要求它require 'ostruct',或者rails可以默认使用它。

+1

工作不需要'ostruct',谢谢 – Steve