Home Is there a way to update a field in rails if same value exists for a different field maintaining its uniqueness?
Reply: 2

Is there a way to update a field in rails if same value exists for a different field maintaining its uniqueness?

Saurabh
1#
Saurabh Published in 2018-02-08 20:57:34Z

I am working on user's model in which users will be sorted on the basis of sort_order for them. What I am trying to achieve is that if we set same sort_order for a new user or update existing user, all users with same sort_order are incremented. For example we have 3 user types with their sort_order as follows


Gold with sort_order as 1

Diamond with sort_order as 2

Platinum with sort_order as 3


Updating Gold to 2 should result in Diamond increasing to 3 and Platinum increasing to 4.

Is there a way to do this in Rails?

Mitch
2#
Mitch Reply to 2018-02-08 22:13:26Z

Sure, have you heard of after_save?

You can define a method to run as a callback every time an object is saved. In this case, you probably only want it to run if the sort order has changed.

Below is some pseudocode - this checks for other models with the same sort_order and increments them. Note this will cascade - the after_save will also be called on models that are incremented, and so should end up updating everything that needs to be updated.

class Foo
  after_save :update_sort_orders, if: :sort_order_changed?

  def update_sort_orders
    Foo.where(sort_order: sort_order).where.not(id: id).each do |foo|
      foo.update_attributes(sort_order: foo.sort_order + 1)
    end
  end
end
Saurabh
3#
Saurabh Reply to 2018-02-08 22:08:58Z

This issue is resolved now. What i did is that I checked first if record with same sort_order is present.

def check_for_duplicates(sort_order)
    foo_list = Foo.all.sort_by { |hash| hash[:sort_order].to_i }
    foo_list.each do |foo|
      if foo['sort_order'] == sort_order
        foo.update_attributes(sort_order: sort_order+ 1)
        sort_order = foo['sort_order']
      end
    end
  end

`

Hope this helps someone!!!!! :)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300929 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO