The correct way to add an inactive custom method to the Active Resource class

I have a route that looks like this:

/orders/preview 

It returns something like:

 <order><total>100</total></order> 

I want to add this method to the active resource class. What is the best way to do this?

I started to do something like this:

 class Order < ActiveResource::Base def self.preview(params = {}) post(:preview, params) end end 

This works, but I get the Net::HTTP response back, and not the Order object. What am I doing wrong?

+4
source share
2 answers

I'm not sure about POST , but if you just wanted to do a GET . Have you tried this?

http://api.rubyonrails.org/v3.2.1/classes/ActiveResource/Base.html#method-c-find

 Order.find(:all, :from => :preview) # => GET /orders/preview.json 
0
source

I had a similar problem with handling different formats ... I solved this by explicitly specifying which formats I want to use as follows:

in the ActiveResource model, set the self.format parameter

 class Order < ActiveResource::Base self.site = "http://lbv.me" self.format = :json end 

In the ActiveRecord model, if you use the reply_with method, you really have to specify in what format you expect the response, for example:

 class UsersController < ApplicationController respond_to :html, :json def show @user = User.find(params[:id]) respond_with @user end . . . end 
0
source

Source: https://habr.com/ru/post/1381582/


All Articles