Alex
Alex

Reputation: 2518

Association callbacks on a has_many-through relationship

I am using a association callback (:before_add) for a has_many-through association. Consider the following setup:

class AccessLevel < ActiveRecord::Base

  belongs_to :user
  belongs_to :post

  enum :level => [:manager, :publisher]

end

class User < ActiveRecord::Base
  has_many :access_levels
end

class Post < ActiveRecord::Base
  has_many :access_levels

  AccessLevel.levels.each_pair{|k, v|
    has_many k.pluralize.to_sym, -> { where(:"access_levels.level" => AccessLevel.levels[k]) },
            :through => :access_levels,
            :source => :user,
            :class_name => "User",
            :before_add => -> (a,b) {
              # a is a post
              # b is a user
              # where is the access level?
              # I'd like to set the :level attribute of the join model...
            }

  }

end


p = Post.first
p.publisher_ids = [1, 5]
p.reload!
p.publishers
=> []

Upvotes: 0

Views: 170

Answers (1)

Alex
Alex

Reputation: 2518

Ok, I found the solution just 2 minutes later ;)

It turns out, that I don't even need an association callback.

class Post

  AccessLevel.levels.each_pair{|k, v|
    has_many :"post_#{k}_access_levels", -> { merge(AccessLevel.send(k)) }, :class_name => "AccessLevel"
    has_many k.pluralize.to_sym, :through => :"post_#{k}_access_levels", :source => :user, :class_name => "User"
  }

end

I added another has_many association for each level which also holds the condition. The has_many-through association than adds this condition to new records automatically .

Upvotes: 1

Related Questions