Output formed by json with rails 3

I am using rails 3.0.3

Javascript autocomplete automatically requires data

{ query:'Li', suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'], data:['LR','LY','LI','LT'] } 

My action

  def autocomplete @query = params[:query] @customers = Customer.where('firstname like ?', "%#{@query}%") render :partial => "customers/autocomplete.json" end 

My opinion

 { query:'<%= @query %>', suggestions: <%= raw @customers.map{|c| "#{c.firstname} #{c.lastname}" } %>, data: <%= raw @customers.to_json %> } 

he returns

 { query:'e', suggestions: ["customer 1", "customer 2"], data: [1, 3] } 

it does not work, because the data for offers / data must be between a simple quote ...

I cannot use the to_json method because it will return all the contents of my object.

Any suggestion?

amuses

+3
source share
3 answers

Note : this is an obsolete option, Jbuilder is the best option. p>


There are two ways to approach this. If you just need a subset of the fields in the object, you can use :only or :except to exclude what you don't want.

 @customer.to_json(:only => [:id, :name]) 

in your example, it looks like you need to return json in a specific format, so just serializing the array of results will not work. The easiest way to create a custom json response is with a Hash object:

 render :json => { :query => 'e', :suggestions => @customers.collect(&:name), :data => @customers.collect(&:id) } 

I tried using partials to create json responses, but this does not work much the same way as just using Hash for this.


Formatting the first and last names as a single line is something you are likely to do a lot in your views, I would recommend moving this to a function:

 class Customer < ActiveRecord::Base ... def name "#{first_name} #{last_name}" end def name=(n) first_name, last_name = n.split(' ', 2) end end 

Just some handy features that make your life a little easier and your controllers / views cleaner.

+10
source

If Adam’s answer doesn’t work for you, this can do it (admittedly not the most elegant solution):

 { query:'<%= @query %>', suggestions: [<%= raw @customers.map{|c| "'#{c.firstname} #{c.lastname}'" }.join(", ") %>], data: [<%= raw @customers.map{|c| "'#{c.id}'" }.join(", ") %>] } 
+1
source

I saw something like this in .erb:

 <%= raw { :query => @query, :suggestions => @customers.map{|c| "#{c.firstname} #{c.lastname}" }, :data => @customers }.to_json %> 

If you think that data will be consumed by other programs as presentation logic, this may make sense to you.

FWIW I like it.

+1
source

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


All Articles