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)
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')
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)
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
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') %>
精彩评论