Trouble defining finder method in my application

时间:2016-02-12 21:07:13

标签: mysql ruby-on-rails methods undefined finder

I’m using Rails 4.2.3 and MySQL 5.5.37. I want to write a finder method for my model, so I have written this (./app/models/user_object.rb):

View view1 = getLayoutInflater().inflate(R.layout.customtab, null);
view1.findViewById(R.id.icon).setBackgroundResource(R.drawable.my1);
tabLayout.addTab(tabLayout.newTab().setCustomView(view1));


View view2 = getLayoutInflater().inflate(R.layout.customtab, null);
view2.findViewById(R.id.icon).setBackgroundResource(R.drawable.my2);
tabLayout.addTab(tabLayout.newTab().setCustomView(view2));


View view3 = getLayoutInflater().inflate(R.layout.customtab, null);
view3.findViewById(R.id.icon).setBackgroundResource(R.drawable.my3);
tabLayout.addTab(tabLayout.newTab().setCustomView(view3));

...

However, when I attempt to invoke the method within a controller like so

class UserObject < ActiveRecord::Base

  validates :day, :presence => true
  validates_numericality_of :total
  validates :object, :presence => true

  def find_total_by_user_object_and_year
    UserObject.sum(:total, :conditions => ['user_id = ?', params[:user_id], 'object = ?', params[:object], 'year(day) = ?', params[:year]])
  end

end

I get the following error

@my_total = UserObject.find_total_by_user_object_and_year(session["user_id"], 3, @year)

What is the right way to define my finder method?

1 个答案:

答案 0 :(得分:2)

Use dflist <- Filter(is.data.frame, as.list(.GlobalEnv)) to define class method:

self.method

In this case def self.find_total_by_user_object_and_year sum(:total, :conditions => ['user_id = ?', params[:user_id], 'object = ?', params[:object], 'year(day) = ?', params[:year]]) end inside class method definition is redundant, besause it is same as UserObject. Now you can write:

self