Improved lookup(), create_if_not_exists() and create_or_update() with name lookup.
This commit is contained in:
parent
893fc79dee
commit
32ea7c6c01
1 changed files with 25 additions and 14 deletions
|
@ -58,9 +58,14 @@ class ApplicationModel < ActiveRecord::Base
|
||||||
cache = self.cache_get( data[:name] )
|
cache = self.cache_get( data[:name] )
|
||||||
return cache if cache
|
return cache if cache
|
||||||
|
|
||||||
record = self.where( :name => data[:name] ).first
|
records = self.where( :name => data[:name] )
|
||||||
|
records.each {|record|
|
||||||
|
if record.name == data[:name]
|
||||||
self.cache_set( data[:name], record )
|
self.cache_set( data[:name], record )
|
||||||
return record
|
return record
|
||||||
|
end
|
||||||
|
}
|
||||||
|
return
|
||||||
else
|
else
|
||||||
raise "Need name or id for lookup()"
|
raise "Need name or id for lookup()"
|
||||||
end
|
end
|
||||||
|
@ -68,24 +73,30 @@ class ApplicationModel < ActiveRecord::Base
|
||||||
|
|
||||||
def self.create_if_not_exists(data)
|
def self.create_if_not_exists(data)
|
||||||
if data[:name]
|
if data[:name]
|
||||||
record = self.where( :name => data[:name] ).first
|
records = self.where( :name => data[:name] )
|
||||||
return record if record
|
records.each {|record|
|
||||||
|
return record if record.name == data[:name]
|
||||||
|
}
|
||||||
elsif data[:locale] && data[:source]
|
elsif data[:locale] && data[:source]
|
||||||
record = self.where( :locale => data[:locale], :source => data[:source] ).first
|
records = self.where( :locale => data[:locale], :source => data[:source] )
|
||||||
return record if record
|
records.each {|record|
|
||||||
|
return record if record.source == data[:source]
|
||||||
|
}
|
||||||
end
|
end
|
||||||
self.create(data)
|
self.create(data)
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.create_or_update(data)
|
def self.create_or_update(data)
|
||||||
if data[:name]
|
if data[:name]
|
||||||
record = self.where( :name => data[:name] ).first
|
records = self.where( :name => data[:name] )
|
||||||
if record
|
records.each {|record|
|
||||||
|
if record.name == data[:name]
|
||||||
record.update_attributes( :data => data[:data] )
|
record.update_attributes( :data => data[:data] )
|
||||||
else
|
return record
|
||||||
|
end
|
||||||
|
}
|
||||||
record = self.new( data )
|
record = self.new( data )
|
||||||
record.save
|
record.save
|
||||||
end
|
|
||||||
return record
|
return record
|
||||||
else
|
else
|
||||||
raise "Need name for create_or_update()"
|
raise "Need name for create_or_update()"
|
||||||
|
|
Loading…
Reference in a new issue