Rails集合_选择Has_Many Through [英] Rails Collection_Select Has_Many Through

查看:80
本文介绍了Rails集合_选择Has_Many Through的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个拥有许多帐户的用户.我想使用collection_select来让用户选择他们要使用的帐户.选择需要在user_accounts表中分配给该用户的所有帐户中进行选择,但是选择需要检查帐户表以获取下拉菜单需要显示的帐户的名称.

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

如果我使用以下选项,则选择有效,但仅显示account_id:

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

我尝试将collection_select替换为:

I tried replacing the collection_select with:

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

返回以下错误:

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

我尝试通过map函数合并这两个表,但未成功:

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

此选项给我以下错误:

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

推荐答案

您可以为此使用OpenStruct:

You can use OpenStruct for this:

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

但是可能您应该要求它 require'ostruct',或者也许rails默认具有它.

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

这篇关于Rails集合_选择Has_Many Through的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆