简体   繁体   中英

Ruby on Rails - delegate devise member on has_and_belongs_to_many association

I have a has_and_belongs_to_many association between keywords and groups and then a groups belongs_to member association between group and devise.

class Keyword < ActiveRecord::Base
  has_and_belongs_to_many :groups
  delegate :member, to: :groups
  validate :keywords_within_limit, on: :create

  def keywords_within_limit
    if self.member.keywords(:reload).count >= self.member.keyword_limit
       errors.add(:keyword, "exceeded limit")
    end
  end
end

Im trying access my current members methods using delegate but I am getting the error NoMethodError - undefined method member for #<ActiveRecord::Associations::CollectionProxy []>:

I can see member is a method by doing self.methods

Why can't I access my members methods using delegate ?

From what I can see there is a many to many mapping between keyword and group. So the groups method would return a collection of groups and not a single record for group. So when you delegate 'member', it is delegated to a collection of groups rather than a group object as you are expecting.

The #<ActiveRecord::Associations::CollectionProxy [] > in your error message is the groups collection.

If you are looking to collect members of all the groups you may need to do something like:

def members
  groups.collect { |group| group.member }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM