RubyOnRails
15 八月 2010 | View Comments
In this commit we found we big improvement.
They add :inverse_of for active_record association
What is that used for?
Here is the example from commit message
class Man < ActiveRecord::Base
has_one :face, :inverse_of => :man
end
class Face < ActiveRecord::Base
belongs_to :man, :inverse_of => :face
end
m = Man.first
f = m.face
If we don’t have :inverse_of, f.man will be different object, not m@ object and what's more active_record will fire another sql query if you can @f.man.
After we add :inverse_of option, @ m == f.man , and @f.man will not fire a sql query.
But now :inverse_of only works for has_one, has_many. It also supplies inverse support for belongs_to
associations where the inverse is a has_one and it’s not a polymorphic.
I think DataMapper need change their website why DataMapper. Active Record has Identity Map now
Thanks
h-lame for giving us this very useful feature which also have sufficient test.
Tagged in 2.3.6, active_record, inverse_of, RubyOnRails
RubyOnRails,Tips
1 四月 2010 | View Comments
Assuming We have Member model.
And one record with name Hnery Miller, with state draft
I have two conditions:
condition1 = ['name like ?','Hnery%']
condition2 = ['state = ?','draft']
What I gonna do is merge these two conditions, using Rails ActiveRecord buildin method merge_conditions
Member.first(:conditions => Member.merge_conditions(condition1,condition2))
Tagged in active_record, RubyOnRails, Tips
RubyOnRails,Tips
30 三月 2010 | View Comments
If you want to enhance ActiveRecord, what you need do?
Write a piece of code in lib like this
# Usage
# =========
# class SomeModel
# money :amount,:consideration_value
# end
#
# options
# ========
# precision => 2
# delimiter => ","
module Moneyable
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
include ::CurrencyRounding
def money(*names)
include CurrencyRounding
if names.last.kind_of?(Hash)
options = names.pop
else
options = {}
end
cattr_accessor :variables_need_format
names.each do |name|
self.variables_need_format ||= []
self.variables_need_format << name.to_sym
define_method "formatted_#{name.to_s}" do
nice_rounding_with_format(send(name),options)
end
end
end
end
end
Then Hack AcitveRecord
puts code below in enviroment.rb
# in 'Rails::Initializer.run do |config|' block
# if there is 'no config.after_initialize'
config.after_initialize do
ActiveRecord::Base.send(:include, Moneyable)
end
Tagged in active_record, metaprograming, RubyOnRails