On Sep 24, 10:44pm, chandrakant jain [email protected] wrote:
:status => '1'
)
sql = ActiveRecord::Base.connection();
sql.execute “SET autocommit=0”;
sql.begin_db_transaction
id, value =
sql.update "UPDATE chsdesk3
. units
SET units.assigned=‘1’ "
end unless @total_unit_count.nil?
Based on your previous post:
http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/fa60e491ea450a60
I’d start by suggesting that you forget that
ActiveRecord::Base.connection EXISTS. Executing raw SQL against the DB
is certainly a powerful tool, but in this case it’s like using a
bazooka to swat flies.
For example, this is probably close to the intent you’re going for:
Unit.transaction do
@units = Unit.where(:assigned => false)
@units.each do |unit|
MemberProperty.create(:unit => unit, :member_type =>
‘Regular’, :status => 1)
unit.update_attribute(:assigned, true)
end
end
You could also pull the two lines inside the loop into a method on
Unit:
class Unit
def create_initial_property
MemberProperty.create(:unit => self, :member_type =>
‘Regular’, :status => 1)
update_attribute(:assigned, true)
end
end
then the code becomes:
Unit.transaction do
@units = Unit.where(:assigned => false)
@units.each do |unit|
unit.create_initial_property
end
end
If the @units variable isn’t used anywhere else, you could also just
combine the two statements and skip it entirely.
There are also some shorter ways to write the MemberProperty creation,
but they depend on how it’s associated to Unit - is it
‘has_one :member_property’ or ‘has_many :member_properties’?
–Matt J.