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
工作不需要'ostruct',謝謝 – Steve