【问题标题】:Private method select called for class - Rails为类调用私有方法选择 - Rails
【发布时间】:2024-04-21 15:00:01
【问题描述】:

我的控制器中有以下代码:

array = Contact.select(:name).distinct

这个想法是,这将创建一个具有唯一 :name 属性的所有 Contact 模型的数组。但是,它抛出了这个错误:

NoMethodError (private method 'select' called for Contact:Class)

这里有什么误解?不管怎样,调用这行代码的方法并没有在控制器中定义为私有的。

编辑:

这是实际代码:

控制器

class FluidsurveysController < ApplicationController

  def index
  end

  def import_contacts
    @survey_provider = FluidsurveysProviders::SurveyProvider.new()

    @current_month = Time.new.strftime("%B%Y%d")

    fs_contact_list_array = csv_to_array(params[:file].tempfile)
    @fs_contacts_array = []

    fs_contact_list_array.each do |hash|
      @fs_contacts_array << Contact.new(hash)
    end

   array = Contact.select(:name).distinct
   end
end

型号

class Contact
  include ActiveModel::Model
  attr_reader :client_id, :client_name, :branch_id, :branch, :short_name, :unit_id, :membership_id,
              :first_name, :last_name, :date_of_birth, :change_date_time, :membership_type,
              :home_phone, :email_address, :anniversary_years


  def initialize(fs_contact_hash = {})
    @client_id = fs_contact_hash.fetch('ClientID')
    @client_name = fs_contact_hash.fetch('ClientName')
    @branch_id = fs_contact_hash.fetch('branchID1')
    @branch = fs_contact_hash.fetch('branch')
    @name = fs_contact_hash.fetch('ShortName')
    @unit_id = fs_contact_hash.fetch('UnitID')
    @membership_id = fs_contact_hash.fetch('MemberID')
    @first_name = fs_contact_hash.fetch('FirstName')
    @last_name = fs_contact_hash.fetch('LastName')
    @date_of_birth = fs_contact_hash.fetch('DateOfBirth')
    @change_date_time = fs_contact_hash.fetch('ChangeDateTime')
    @membership_type = fs_contact_hash.fetch('MembershipType')
    @home_phone = fs_contact_hash.fetch('HomePhone')
    @email_address = fs_contact_hash.fetch('EMail1')
    @anniversary_years = fs_contact_hash.fetch('Years')
  end
end

【问题讨论】:

  • FWIW:Rails API 参考以这个确切的用法为例:api.rubyonrails.org/classes/ActiveRecord/…
  • 你写的“没有在 controller 中定义为私有”,你的意思是 model 吗?
  • 不,我的意思是方法本身不是私有方法。但是,我的模型属性也不是私有的。
  • 也许可以试试Contact.all.select(:name)
  • 你的类是 ActiveRecord 对象吗?

标签: ruby-on-rails ruby methods controller


【解决方案1】:

根据您的错误消息,我很确定您的模型不是 ActiveRecord 对象。

如果您想使用ActiveRecord#select,请像这样定义您的模型。

class Contact < ActiveRecord::Base

您还需要在数据库中定义属性而不是通过 attr_reader 来通过 ActiveRecord 访问它们。见http://guides.rubyonrails.org/getting_started.html#running-a-migration

【讨论】:

  • 如果 Arjan 是正确的,this 可能有助于进一步解释错误。
  • 就是这样...感谢您的额外解释,继续我的学习。
【解决方案2】:

您似乎使用的是旧版本的 Rails,特别是 2.3.whatever 版本。在那里,select 方法在 ActiveRecord 模型类上确实是私有的(因为它继承自 Kernel 模块,该模块是每个 Ruby 对象的一部分并且服务于完全不同的目的),因此不打算像这样使用它是在 Rails 3 和 Rails 4 中完成的。

在 Rails 2.3 中,您可以使用以下语法获得类似的结果:

Contact.all(:select => "DISTINCT name")

这将返回一个联系人数组,其中只有 name 属性集。

【讨论】:

  • @Luigi 如果您粘贴了错误的完整堆栈跟踪,这会立即更清楚。
最近更新 更多