To display the searched item in the same page - ruby-on-rails

The following code present in srches_controller
def index
#srches = Srch.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #srches }
end
.
.
.
def search
#srch=Srch.find(:all,
:conditions => ["name LIKE ? OR address LIKE ?", "%#{params[:search]}%", "%#{params[:search]}%"])
end
The searched item is now displayed in the new search page.
But I need to display the searched item in the same index page.
What is the solution?

You can pass parameter search to index page and search your results with:
def index
#srches = Srch.scoped
if params[:search].present?
#srches = #srches.where(['name LIKE ? OR address LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%"])
end
respond_to do |format|
format.html
format.json { render :json => #srches }
end
end
or you can set scope in your model:
scope :search, lambda{|query|
if query.present?
where(['name LIKE ? OR address LIKE ?', "%#{query}%", "%#{query}%"])
end
}
and call it in controller with:
#srches = Srch.search(params[:search])

You can use meta search gem for your index method, it looks some thing like this -
def index
#srches = Srch.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #srches }
end
In this case if search parameters were present it will search in your table else it will return all the records from your table.

Related

Rails - How to render json with extra field in index controller method

I'm using Rails 4.0.2 with paperclip for image upload in my project. Also I need to send a full image path of paperclip. So I can do it with add new field and set image path manually in my show controller method for particular record.
show
def show
respond_to do |format|
format.html
format.json { :json => JSON::parse(#demo.to_json.merge("new_field" => #demo.image_url.url).to_json}
end
end
When I view Json for any of my record, this is will showing good.
{
id: "1",
name: "demo",
new_field: "/demo/1/original/file.jpg"
}
In same scenario, I need to get the full image path of paperclip image for all records when I am requesting to index method on controller
index
def index
#demos = Demo.all
respond_to do |format|
format.html
format.json { :json => Demo.all.to_json}
end
end
I tried some of codes, but I don't know how exactly to write
def index
#demos = Demo.all
#demos.each do |demo|
new_field = {"new_field" => #demo.image_url.url}
# After I stucked with logic, how to uppend with 'demo'.
end
respond_to do |format|
format.html
format.json { :json => Demo.all.to_json}
end
end
How do I iterate my individual Demo model and How to merge full image path into each record.
I found the solution for my question,
def index
#demos = Demo.all
#demos_data = []
#demos.each do |demo|
new_field = {"new_field" => #demo.new_field.url}
demo = JSON::parse(demo.to_json).merge(new_field)
#demos_data << demo
end
respond_to do |format|
format.html
format.json { :json => #demos_data}
end
end
I suggest you to use two approaches, 1)use active model serializer to expose json response. 2) use jbuilder library to expose custom fields. Still you need help please let me know.
Try this:-
def index
#demos = Demo.all
#demos_data = []
#demos.each do |demo|
demo["new_field"] = #demo.image_url.url
#demos_data << demo
end
respond_to do |format|
format.html
format.json { :json => #demos_data}
end
end
maybe you can try:
def index
#demos = Demo.all
#demos.map do |demo|
new_field = {"new_field" => #demo.image_url.url}
demo.attributes.merge(new_field)
end
respond_to do |format|
format.html
format.json { :json => #demos}
end
end
attributes method returns a hash of all the object attributes, just need merge new key-value into the returned hash.
Another way of doing it is in your controller where you are rendering the json
render json: #merchants,
include: {
offers: {
except: [:created_at, :updated_at],
include: {
categories: {
except: [:created_at, :updated_at]
}
}
},
location: {
methods: :country_name,
except: [:created_at, :updated_at]
}
},
except: [:created_at, :updated_at]
Note the methods: :country_name, there you can render methods from your model as json attributes. and through include: ... you can eager load and render related models.

Rails - Add index key for json parsed value

I am using rails 4.0.2. For my mobile api, I need to send JSON values to that. Here I face some problems to sending JSON . I want to customize my JSON with index key
For example, when I request index of my cities controller,
http:localhost:3000/cities.json
I got JSON value like this,
[
{"id":1,"name":"AAAA"},
{"id":2,"name":"BBBB"},
{"id":2,"name":"CCCC"}
]
But I want to surrounded with some named object or array.
{
"cities" :
[
{"id":1,"name":"AAAA"},
{"id":2,"name":"BBBB"},
{"id":2,"name":"CCCC"}
]
}
Now I tried in my controller,
def index
#cities = City.all
respond_to do |format|
format.html
format.json{ render :json => #cities.to_json(:methods => [:image_url]) }
# :methods => [:image_url] this is related to paperclip gem
end
end
Try this first as:-
def index
#cities = City.all
cit ={'cities' => #cities}
respond_to do |format|
format.html
format.json{ render :json => cit}
end
end
After that try as:-
def index
#cities = City.all
cit ={'cities' => #cities}
respond_to do |format|
format.html
format.json{ render :json => cit.to_json(:methods => [:image_url]) }
end
end

How do I override Kaminari pagination when rendering JSON in the respond_to block?

I want to override Kaminari's pagination when rendering JSON, or tell it to return all with pagination.
In App1, I am using ActiveResource to access App2's Group model:
class Group < ActiveResource::Base
self.site = "http://www.app2.com:3000"
end
Here's App2's Group model:
class Group < ActiveRecord::Base
default_scope order('name asc')
paginates_per 10
This is my controller. The Group.search stuff is ransack:
class GroupsController < ApplicationController
# GET /groups
# GET /groups.json
def index
#search = Group.search(params[:q])
#groups = #search.result.page params[:page]
respond_to do |format|
format.html # index.html.erb
format.json { render json: #groups }
end
end
I've added eleven groups to App2. In the console of App1 I get:
[45] pry(main)> Group.all.count
=> 10
What is the best way to do this without changing the HTML pagination rendering?
You can prepare all the common logic you need but only apply pagination for the HTML format:
def index
#search = Group.search(params[:q])
#groups = #search.result
respond_to do |format|
format.html { #groups = #groups.page(params[:page]) }
format.json { render :json => #groups }
end
end
You can run different code in different formats:
def index
respond_to do |format|
format.html {
#search = Group.search(params[:q])
#groups = #search.result.page params[:page]
} # index.html.erb
format.json {
render json: Group.all
}
end
end

Rails restful select in url

If I enter the following URL in a browser, I get a list of client records:
http://localhost:5000/clients.json
Now, I would like to be able the select certain clients via the URL. Is something like this possible:
http://localhost:5000/clients.json?locname=ys
This is my clients_controller.rb for index:
def index
#clients = Client.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #clients }
end
end
THANKS!
This should do the job:
def index
#clients = Client.scoped
#clients = #clients.where(:locname => params[:locname]) if params[:locname].present?
respond_to do |format|
format.html # index.html.erb
format.json { render json: #clients }
end
end

how can i include a variable at each array in rails?

I have user model and i want the list of users as json and i want the length of name along with the response for each user but i do not how i can do this? I have tried as shown below and it resulted in double render error. If i take the respond_to from the loop then it returns nothing. so please help me.
#users = User.all
#users.each do |user|
length = user.name.count
respond_to do |format|
format.json { render json: #users.to_json(:include => [:length]) }
end
end
I want the response to be like
[{"user":{"name":asgd,"id":1,"length":"4"}},{"user":{"name":asdfg,"id":2,"length":"5"}}]
Try:
#users = User.all
all_users = Array.new
#users.each do |user|
all_users << {"id" => user.id, "name" => user.name,"length" => user.name.size}
end
respond_to do |format|
format.json { render json: all_users.to_json }
end

Resources