我有以下关联:
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会删除所有用户 - &gt;品牌关联,然后只重新添加我刚刚提交的表单的关联。
如何将其范围仅移除属于子域中定义的当前公司的品牌关联?
答案 0 :(得分: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)
如果有人有更好的想法,我仍然希望听到它,因为我不知道这是否是最佳选择..