简体   繁体   English

Ruby on Rails-has_and_belongs_to_many协会的委托devise成员

[英]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. 我有一个has_and_belongs_to_many之间的关联keywordsgroups ,然后groups belongs_to member组和设计之间的关联。

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 []>: 我正在尝试使用delegate访问我当前的成员方法,但我收到错误NoMethodError - undefined method member for #<ActiveRecord::Associations::CollectionProxy []>:

I can see member is a method by doing self.methods 我可以看到member是通过self.methods方法

Why can't I access my members methods using delegate ? 为什么我不能使用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. 因此,groups方法将返回组的集合,而不是组的单个记录。 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. 错误消息中的#<ActiveRecord::Associations::CollectionProxy [] >是groups集合。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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