开发者

Rails HABTM Scoping to current subdomain

I have the following associations:

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

While editing a user I am using the checkbox list of brands. So that I can assign users 'access' to brands, the brands that show up are only the brands that belong to the current company (defined by the subdomain [using subdomain_fu]).

The problem I am running into is that when using the defa开发者_运维百科ult HABTM functionality and the checkbox list, upon save, Rails removes ALL user->brand associations, then re-adds just the ones for the form I just submitted..

How do I scope that to only remove associations of brands who belong to the current company, defined in the subdomain?


Here is what I did.. I ended up placing it in the controller, and manually adding ALL the outside values before saving the user.

# 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)

If anyone has a better idea, I would still love to hear it, as I don't know if this is the best option here..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜