Ruby on Rails Sunday, October 2, 2011

On Sep 24, 10:44 pm, chandrakant jain <ckjai...@gmail.com> wrote:
> 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 = Unit.select('id').where('assigned = 0')
>     @total_unit_count = @total_unit.count
>
>   1.upto @total_unit_count do |i|
>         MemberProperty.create(
>         :unit_id =>  @total_unit[i-1].id,
>         :member_type => 'Regular',
>         :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 Jones

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment