Rails Collection_Select Has_Many Through

时间:2014-07-11 01:32:13

标签: ruby-on-rails ruby forms has-many-through

我的用户有很多帐户。我想使用collection_select让用户选择他们想要使用的帐户。 select需要在user_accounts表中选择分配给用户的所有帐户,但select需要检查accounts表以获取下拉菜单需要显示的帐户名称。

#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 个答案:

答案 0 :(得分:1)

您可以使用OpenStruct:

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

但可能你应该要求它require 'ostruct',或者默认情况下rails可能需要它。