Reputation: 14514
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
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
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
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
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