Rails beginner
Rails beginner

Reputation: 14514

Rails how to create a class method self to keep things DRY?

I repeat this code many times. The only thing that changes is the name in conditions.

find(:all, :conditions => {:name => 'hans'}, :group => 'dato').map(&:klik)

I am trying to make some class method in the model. So I can keep it DRY.

I have been trying this and it is not working.

def self.grafdata(name)
    find(:all, :conditions => {:name => '(name)'}, :group => 'dato').map(&:klik)
end

ERROR: uninitialized constant ActionView::CompiledTemplates::Lars

I want to be able to write Model.grafdata(Hans), Model.grafdata(Lars)

Upvotes: 2

Views: 892

Answers (4)

everyna
everyna

Reputation: 71

You can use named_scope:

class Model

  named_scope :grafdata, lambda {|name| {:conditions => ["name = ?", name], :group => 'dato'}}

end

Then called:

Model.grafdata('Lars').map(&:klik)

Upvotes: 3

Rails beginner
Rails beginner

Reputation: 14514

Instead of '(name)' it should only be (name)

def self.grafdata(name)
    find(:all, :conditions => {:name => (name)}, :group => 'dato').map(&:klik)
end

And the view: <%= Reklamer.grafdata('Lars') %>

Upvotes: -2

Pan Thomakos
Pan Thomakos

Reputation: 34350

I would simply add it as a function to your model:

class Model
  def self.grafdata(name)
    where(name: name).group('dato').map(&:klik)
  end
end

You can then call either of the following:

Model.grafdata('Lars')
Model.grafdata('Hans')

Upvotes: 6

Peer Allan
Peer Allan

Reputation: 4014

Use a module

module MyFinders
  def grafdata(name)
    find(:all, :conditions => {:name => '(name)'}, :group => 'dato').map(&:klik)
  end
end

class Foo < ActiveRecord::Base
  extend MyFinders
end

HTH

Peer

Upvotes: 2

Related Questions