Skip to content Skip to sidebar Skip to footer

Render Queries With Ajax In Rails

I need help or guidance with the following problem. I using ajax to reload dynamically queries from database each time is change in a search form. The purpose is to dynamically

Solution 1:

A better way would be to use jbuilder or RABL which both allow you to easily include associated data in your json response.

In your case here, you would simply need to create a view file at:

app/views/clients/clientjson.json.jbuilder

Then your jbuilder would look something like:

json.array! @clientsdo|client|
  json.id client.id
  json.name client.name
  json.rate client.rate
  json.address client.address
  json.date client.date
  json.numbercomments client.numbercomments

  json.comments client.comments, :subject, :comment, :created_at

  json.country do
    json.name client.country.name
  end

  json.city do
    json.name client.city.name
  end

  json.language do
    json.name client.language.name
  endend

Then change your controller action to:

defclientsjson@search  =  Client.search(params[:q])
  @clients = @search.result

  respond_to do|format|
    format.json
  endend

Which should give you all the associated json nodes you need.

Solution 2:

I agree with using jbuilder or RABL for generating the json. That gives you control over how much or little you need to bring back, and can also generate nested arrays for dependent records, etc.

For some like this, I'd also be tempted to use something like Backbone.JS and handlebars for the javascript templateing. You don't have to, but will more cleanly separate the HTML from the Javascript, making future changes to HTML or JS easier. Any JS templating system is probably better and none, but I've been happy with Backbone and Handlebars.

Post a Comment for "Render Queries With Ajax In Rails"