gpt4 book ai didi

ruby-on-rails - Rails Collection_Select Has_Many 通过

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:44 25 4
gpt4 key购买 nike

我有一个用户有很多帐户。我想使用 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>

我尝试通过 map 函数合并 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

最佳答案

您可以为此使用 OpenStruct:

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

但也许你应该要求它 require 'ostruct',或者 Rails 默认有它。

关于ruby-on-rails - Rails Collection_Select Has_Many 通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24688872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com