这是我的第一个stakoverflow问题,对Rails来说还算新。我已经搜索过以前的类似问题,但似乎无法想出这个问题。我有一个与用户和帐户的has_many关系,我在UserAccount模型(连接表)上有一个额外的布尔属性“account_admin”。我正在尝试在创建新帐户时弄清楚如何设置它。
用户:
class User < ActiveRecord::Base
has_many :user_accounts, :dependent => :destroy
has_many :accounts, :through => :user_accounts
..
end
帐户:
class Account < ActiveRecord::Base
has_many :user_accounts, :dependent => :destroy
has_many :users, :through => :user_accounts
end
UserAccount:
class UserAccount < ActiveRecord::Base
belongs_to :user
belongs_to :account
# includes account_admin boolean
end
我希望能够创建一个帐户,将用户分配到该帐户,并在一个表单中指定一个account_admin。到目前为止我有这个允许我选择帐户中的用户,但我不知道如何在这里设置account_admin布尔值。
= simple_form_for @account do |f|
= f.input :name
= f.input :description
= f.association :users, label_method: :to_label, :as => :check_boxes
= f.button :submit
感谢任何提示。感谢
答案 0 :(得分:0)
class Account < ActiveRecord::Base
attr_accessible :name, :description, :user_accounts_attributes
has_many :user_accounts, :dependent => :destroy
has_many :users, :through => :user_accounts
has_many :user_without_accounts, :class_name => 'User', :finder_sql => Proc.new {
%Q{
SELECT *
FROM users where id NOT IN (Select user_id from user_accounts where account_id = #{id})
}
}
accepts_nested_attributes_for :user_accounts, reject_if: proc { |attributes| attributes['user_id'] == '0' }
def without_accounts
new_record? ? User.all : user_without_accounts
end
end
= simple_form_for @account do |f|
= f.input :name
= f.input :description
- @account.user_accounts.each do |user_account|
= f.simple_fields_for :user_accounts, user_account do |assignment|
= assignment.check_box :user_id
= assignment.label :user_id, user_account.user.name rescue raise user_account.inspect
= assignment.input :account_admin
%hr
- @account.without_accounts.each do |user|
= f.simple_fields_for :user_accounts, @account.user_accounts.build do |assignment|
= assignment.check_box :user_id
= assignment.label :user_id, user.name
= assignment.input :account_admin
%hr
= f.button :submit