代码之家  ›  专栏  ›  技术社区  ›  Rabbott

Rails HABTM作用域到当前子域

  •  0
  • Rabbott  · 技术社区  · 16 年前

    我有以下联想:

    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
    

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

    我如何界定范围,只删除属于当前公司的品牌关联,在子域中定义?

    1 回复  |  直到 16 年前
        1
  •  0
  •   Rabbott    16 年前

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