为什么找不到我的 Ruby 模型方法?

Why isn't my Ruby model method being found?

我有联系人、群组以及组成联系人群组的成员的模型,这些联系人群组通过称为成员的关系链接。成员模型使用 :through 属性解析联系人和组之间的多对多关系。

当我尝试向 Contact 模型添加一个名为 suggestions 的新方法并从我的 ContactsController 调用它时,如下所示,我收到一条消息,告诉我找不到该方法。 ContactsController 看起来像这样:

class ContactsController < ApplicationController
  before_action :logged_in_user, only: [:index, :show, :edit, :update, :destroy]
  before_action :set_contact, only: [:show, :edit, :update, :destroy]

  # GET suggestions
  def suggestions
    recipients_string = params[:recipients_field]

    # Call theContact model to list of all of the groups and individual contacts that aren't already in the recipient list
    # and return them as an html unordered list of clickable links
    @suggestions = contacts.suggestions[recipients_string: :recipients_string]

  end
  ...
  ...
end

联系人模型如下:

class Contact < ActiveRecord::Base
  has_many :members
  has_many :groups, :through => :members
  default_scope -> { order(name: :asc) }
  validates :name, presence: true
  validates :email, presence: true

  accepts_nested_attributes_for :members,
                                :reject_if => :all_blank,
                                :allow_destroy => true
  accepts_nested_attributes_for :groups

  def suggestions
      recipients_string = params[:recipients_string]
      # some processing here to ptoduce @suggestions
      @suggestions
  end
end

Contacts 的使用中,我不想利用关系,但我注意到当我调用 contacts.suggestions 时,我得到

undefined method `suggestions' for #<Contact::ActiveRecord_Relation:0x007fd75b32c988>

这与找不到该方法的原因有什么关系吗?我做错了什么?

那是因为 contacts.suggestions return 是一个联系人数组,实际上是一个 Relation 范围为联系人集合而不是单个联系人。

suggestions 被定义为实例方法,因此它应该在单个实例上调用,而不是在集合上调用。

要么更改方法的范围,要么确保 contacts 不是 return 集合。

我认为这是因为您调用了一组联系人的方法。 您的方法只存在于一个联系人

也许试试这个:

 @suggestions = contacts.map{|contact| contact.suggestions[recipients_string: :recipients_string]}

该错误告诉您 contacts 是一个关系,类似于联系人记录的集合。 (我希望它实际上会抱怨没有名为 contacts 的变量或方法)

您的意思是从 params[:id] 定义一个 @contact 变量然后调用 .suggestions 吗?

您的联系人 class 中的 suggestions 方法将不起作用,因为它引用 params,并且这些在模型 class 中不可用,除非您将它们作为参数传递给方法。

您是在 ActiveRecord 关系上调用 suggestions(),而不是在单个联系人上。您需要获取特定的 Contact 实例才能调用此方法。