Lui*_*igi 8 ruby methods controller ruby-on-rails
我的控制器里面有以下代码:
array = Contact.select(:name).distinct
我们的想法是,这将创建一个Contact具有唯一:name属性的所有模型的数组.但是,它抛出了这个错误:
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
根据您的错误消息,我非常确定您的模型不是ActiveRecord对象.
如果您想使用ActiveRecord#select,请定义您的模型.
class Contact < ActiveRecord::Base
Run Code Online (Sandbox Code Playgroud)
您还需要在数据库中定义属性,而不是通过attr_reader来通过ActiveRecord访问它们.请参阅http://guides.rubyonrails.org/getting_started.html#running-a-migration
您似乎使用的是旧版本的Rails,特别是版本2.3.whatever.在那里,该select方法在ActiveRecord模型类中确实是私有的(因为它继承自作为Kernel每个Ruby对象的一部分的模块并且用于完全不同的目的),因此不打算像在Rails 3中那样使用它.和Rails 4.
在Rails 2.3中,您可以使用以下语法获得类似的结果:
Contact.all(:select => "DISTINCT name")
Run Code Online (Sandbox Code Playgroud)
这将返回仅具有name属性集的Contacts数组.