Rails Collection_Select Has_Many Through

て烟熏妆下的殇ゞ 提交于 2021-02-08 06:13:22

问题


I have a user that has many accounts. I want to use a collection_select to have the user select which account they want to use. The select need to select among all the accounts assigned to the user in the user_accounts table, but the select needs to check the accounts table to get the name of the account that the drop down menu needs to display.

#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

If I use the following, the select works, but only displays the 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 %>

I tried replacing the collection_select with:

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

which returns the following error:

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

I tried combining the 2 tables via a map function but also was unsuccessful:

#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 %>

This option gives me the following error:

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

回答1:


You can use OpenStruct for this:

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

But probably you should require it require 'ostruct', or maybe rails has it by default.



来源:https://stackoverflow.com/questions/24688872/rails-collection-select-has-many-through

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!