0

这是我的第一个 stakoverflow 问题,对 Rails 来说相当新。我已经搜索了以前的类似问题,但似乎无法弄清楚这个问题。我与用户和帐户有一个 has_many through 关系,并且我在 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

用户帐号:

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

感谢任何提示。谢谢

4

1 回答 1

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
于 2013-06-25T15:28:56.400 回答