alternate better way to write

The following is working but i am not sure if this is a better way to
write it. Can someone suggest better way to write following code

    @total_unit ='id').where('assigned = 0')
    @total_unit_count = @total_unit.count

  1.upto @total_unit_count do |i|
        :unit_id => @total_unit[i-1].id,
        :member_type => 'Regular',
        :status => '1'
    sql = ActiveRecord::Base.connection();
    sql.execute "SET autocommit=0";
    id, value =
    sql.update "UPDATE `chsdesk3`. `units`
    SET units.assigned='1' "
  end unless @total_unit_count.nil?

Based on your previous post:

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)

You could also pull the two lines inside the loop into a method on

class Unit
  def create_initial_property
    MemberProperty.create(:unit => self, :member_type =>
'Regular', :status => 1)
    update_attribute(:assigned, true)

then the code becomes:

Unit.transaction do
  @units = Unit.where(:assigned => false)

  @units.each do |unit|

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 Jones

Not only in the unnecessary power, but in the fact that it's dangerous
on both ends!

Someone once sigquoted Jethro Tull's "Thick as a Brick": "The poet and
the wise man stand behind the gun". I replied: "but only the poet
stands behind the bazooka!" :wink:


"SQL is like violence. If it doesn't solve your problem, you're not using enough of it."
-- anon