0

我有以下关联:

class User < ActiveRecord::Base
  has_and_belongs_to_many :brands, :join_table => 'brands_users'
  has_and_belongs_to_many :companies, :join_table => 'companies_users'
end

class Brand < ActiveRecord::Base
  belongs_to                :company
  has_and_belongs_to_many   :users, :join_table => 'brands_users'
end

class Company < ActiveRecord::Base
  has_and_belongs_to_many   :users, :join_table => 'companies_users'
  has_many :brands, :order => :name
end

在编辑用户时,我正在使用品牌复选框列表。这样我就可以为用户分配品牌的“访问权限”,显示的品牌只是属于当前公司的品牌(由子域 [使用 subdomain_fu] 定义)。

我遇到的问题是,当使用默认的 HABTM 功能和复选框列表时,在保存时,Rails 会删除所有用户->品牌关联,然后只为我刚刚提交的表单重新添加这些关联。

如何将其范围限定为仅删除属于当前公司的品牌关联,在子域中定义?

4

1 回答 1

0

这就是我所做的......我最终将它放在控制器中,并在保存用户之前手动添加所有外部值。

# if admin clears all brand checkboxes the browser will ignore this change,
# so we will provide an empty array if this is the case, to make sure that
# the brands are removed
params[:user][:brand_ids] ||= []

@user = User.find(params[:id])

# collect brands for this user that are not part of this form to ensure they 
# arent removed by the rails habtm functionality
other_brands = @user.brands(:conditions => ['id NOT IN (?)', @company.brands])
other_brands.each do |ob|
  params[:user][:brand_ids] << ob.id
end

# reload the user object with the brands selected on this form, as well as 
# all their brands from other companies
@user.reload(params)

如果有人有更好的主意,我仍然很想听听,因为我不知道这是否是这里的最佳选择..

于 2010-04-22T23:35:17.233 回答