Thursday, 20 November 2014

ActiveResource Custom calls response on get method

In this article i am going to explain one problem on active resource custom calls on get method and what the solution on that. Lets see whats the problem while you are making any active resource get calls. Lets see one example code snippet.

User.get(:active)  # GET /users/active.json
# => [{:id => 1, :name => 'Madhan'}, {:id => 2, :name => 'Ayyasamy'}]

User.get(:active, :awesome => true)  # GET /users/active.json?awesome=true
# => [{:id => 1, :name => 'Madhan'}]

Key Point: The objects returned from the called methods will be just ordinary hash only. It will not be automatically converted into ActiveResource::Base instances.

If you are expecting ActiveResource::Base instances, you have to use "find" class methods with ":from" option. This is the solution for the problem.

Then the new method will be like this

User.find(:all,:from=> :active)  # GET /users/active.json

# => <#User...> <#User...>.... (result as ActiveResource::Base instances).
Then you can use inside the iterations user.first.login_name something like this.

Thanks for reading this article. Hope it will be useful for you.

No comments :

Post a Comment