关于has_many-through关系的关联回调

时间:2014-08-07 13:44:35

标签: ruby-on-rails ruby activerecord

我正在为:before_add关联使用关联回调(has_many-through)。请考虑以下设置:

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
=> []

1 个答案:

答案 0 :(得分:1)

好的,我在2分钟后找到了解决方案;)

事实证明,我甚至不需要关联回调。

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

我为每个级别添加了另一个has_many关联,它也保留了条件。 has_many-through关联比自动将此条件添加到新记录中。