Rails - json.erb template

I am trying to figure out a way to configure JSON with special fields, custom formats, etc. I created the as_json and to_xml method in my model to formulate the object as I need. This works well, but it is careless, because some of my helper methods had to move into the model, because I need formats in helpers and models. I also think that this is a sloppy code and takes the model out of control.

I managed to get the format of json.erb, but I do not think that it works 100% correctly, and the callback is not added either. Anyone get this job

Here is what I got so far.

api calls format.json

the template is called items.json.erb

<% @items.each do |item| %>
<%= { :item => { :id => item.id, :name => item.name }.to_json.html_safe  %>
<% end %>

It works, but it seems weird. Anyone have suggestions or is there a way to do this?

btw did it for a callback to work

<%= params[:callback]+"(" if params[:callback]  %>
<% @items.each do |item| %>
    <%= { :item => { :id => item.id, :name => item.name }.to_json.html_safe  %>
<% end %>
<%= ")" if params[:callback]  %>
+3
source share
3 answers

I think the best way to do this is to skip the template erbif you don't need it, if for some reason. Then you can do something like this:

items = Item.all
render :json => items.to_json(:only => [:id, :name]), :callback => params[:callback]

You can override a method to_jsonin your model to add fields or calling methods.

+6
source

Based on your answer on polarblau, you should override the as_json method and use the methods parameter: include the results of the method in your json

class Item

  def date
    return "1 year and 8 months" #obviously use logic here
  end

  def as_json(args={})
    super(:methods=>[:date], :only=>[:id=>:name])
  end
end
0
source

, :

  • sql / ( , Ruby):

    MyModel.select('col_name_that_needs_renamed AS new_name').order('some_col DESC')

    :

    MyModel.find_by_sql('SELECT col_name_that_needs_renamed AS new_name, foo_col*50 AS math WHERE foo=bar ORDER some_col LIMIT 8')

  • -, ( ) SQL, , , Ruby ( , )

    API Dock to_json

0
source

All Articles