2

Every time, when I'm getting the data from the API request, I require to compare and update records, if any changes was there.

for example i have saved User

    user = User.first
    user.name => 'name_one' 

when i calling to api,api returns me User but name was cahnged to 'name_two'

so i need compare existing user with newly arrived and if name changed replace it

example of calling api

     url= 'my api str'
     result = Curl.get(url)
     JSON.parse(result.body_str).each do |key, value|
      value["commissions"].each do |k, v|


    User.create(name: v["name"],etc... )

  end
end

I will be glad for any suggestions.

Katya
  • 138
  • 10
  • You need to explain what exactly you want: What do you mean by *changes was there*? You mean the api request? How would one request look like? – sebkkom Nov 25 '14 at 11:05
  • You should provide example of your code blocks or responses or requests and server logs is appreciated as well. If your question is not explainable, experienced people can't get the option to help sorting your problem. Hope you understand. Thanks! – Rubyrider Nov 25 '14 at 11:08
  • please provide an example of calling Rails API – Малъ Скрылевъ Nov 25 '14 at 11:24

3 Answers3

3

You can also try the following:

u = User.first
u.name = "name_two"
u.name_changed? #=> true/false
u.name_was #=> "name_one" if it was "name_one"

These are called dirty method and very helpful for this kind of task.

Thanks

Rubyrider
  • 3,567
  • 1
  • 28
  • 34
1

I believe you shall use active record's private method #read_attribute to compare current updated values with stores ones:

if send(:read_attribute, :attr) == self.attr
  # value isn't changed
end

Additional info you can read here:

Validation from controller

You shall validate newly created record from controller:

v['name'] = 'User 1'
user = User.create(name: v['name'])
user.name # => # User 1
Community
  • 1
  • 1
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69
1

Try this code

u = User.first
u.name = "name_two"

u.save if u.changes.include?("name")
slip
  • 63
  • 6