has_many through form and adding attribute to join table

别等时光非礼了梦想. 提交于 2019-12-08 09:50:17

问题


This is my first stakoverflow question and fairly new to Rails. I've searched through previous similar questions but can't seem to figure this one out. I have a has_many through relationship with Users and Accounts and I have an extra boolean attribute "account_admin" on the UserAccount model (join table). I'm trying to figure out how to set this when I create a new Account.

User:

class User < ActiveRecord::Base
  has_many :user_accounts, :dependent => :destroy
  has_many :accounts, :through => :user_accounts
  ..
end

Account:

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

I would like to be able to create an account, assign users to that account, and designate an account_admin all in one form. I have this so far which allows me to select the users in an account but I'm not sure how to set the account_admin boolean here as well.

= 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

Appreciate any tips. Thanks


回答1:


Account model:

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

In form:

= 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


来源:https://stackoverflow.com/questions/17300152/has-many-through-form-and-adding-attribute-to-join-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!