I am rather new to ruby and rails development.
for the past little while, I have been trying to figure out how I can pass params/query string to a rails respond_to block. I am focusing on the json response.
Say I have the following
def index
#employees = Employee.all
respond_to do |format|
format.html
format.json { render json: #employees }
end
end
and I am looking to only get a json response containing employees who have an id that is greater than 500. What would be the best way to go about this.
I have been trying to make the json request using jQuery.ajax() and I know you can pass data to the server that is formatted to a query, but not sure how to make it work.
The above example is only hypothetical. I am only looking for a way to be able to use a query sting when wanting a json response.
Thanks for the help!
Whatever parameters are sent with the request (in the query string) should be available in your controller (check the params variable). Here's one way to get the Employees with id's at & above 500:
Replace
#employees = Employee.all
with
#employees = Employee.find(:all, conditions: ["id >= ?", 500])
Please note that you don't need to pass anything besides the format to that respond_to block.
Related
What i do wrong? I want to return every products which pass condition:
def show
products = Product.select{|x| x[:category_id] == params[:id]}
render json: products
end
When i write
def show
products = Product.select{|x| x[:category_id] == 1}
render json: products
end
it works why the first example doesn't work?
I am pretty sure that there is mismatch in data type.
1=='1' #will be always false
1==1 #will be true
'1'=='1' #will be true as well
And also check for nil value from params[:id]
Please make sure to change as follows
def show
products = Product.select{|x| x.category_id == params[:id].to_i}
render json: products
end
OR
The best solution as suggested by #Eyeslandic is to use .where as it will not check for mismatch in data type. And also you don't have to take care of nil value from params[:id].
You should really be using a where to stop sql from loading all your products.
#products = Product.where('category_is = ?', params[:id])
The being said, if you are sticking to rails restful conventions, the fact you have a param called :id that is the category_id suggests you are on the category controller. So maybe consider changing your logic to:
#category = Category.includes(:products).find(params[:id])
you can then access products via
#category.products
or if your not interested in the category too much maybe
#products = Category.includes(:products).find(params[:id])&.products
With the goal of creating a JSON string, the requirement is to use an existing attribute and assign it, in the JSON output, with the attribute name id.
#valids = Destination.limit(10).select(:name, :long_name, :other_code).as_json(except: :id)
except: :id is being invoked to avoid confusion, as other_code attribute is intended to be the id in the generated JSON.
this will then be transformed into valid JSON via
#valids.to_json
how can other_code be output as id ?
You can do this like that with a simple string instead of symbols.
Destination
.limit(10)
.select('name, long_name, other_code as id')
.as_json
Honestly am new to Ruby on rails but very experience with json and frontend application responses
You can try this. if it work, you can now try it with your database responses. Ensure that column id exist in that your database
def your_definition_here
respond_to do |format|
#valids='999'
format.json do
render json: {id: #valids}.to_json
#render json: {id: #valids.id}.to_json
end
end
end
I have a controller designed to perform simple CRUD operations. The model of my data has an attribute called start_date. What should I do in order to make my API return a JSON response with only the entries with a start_date value between two dates that I can specify in the body of the request?
This is more like a generic question about filtering that could be applied to any API request.
If you make a GET request for an endpoint like example.com/model you would have to pass some parameters, in that case, 2 dates in the URL. So it would be something like this:
example.com/model?start_date=12.12.2017&end_date=15.12.2017
This example is super simple of course. You can pass those dates in different ways like a timestamp or ISO format. that is up to you.
On the backend side, you have to fetch those parameters from the request and perform a query on your model. something like this:
def index
start_date = params[:start_date]
end_date = params[:end_date]
# Make sure to parse the params and transform in a date object
result = Model.where('start_date < ? AND start_date > ?', end_date, start_date)
respond_to do |format|
format.json { render json: result }
end
end
I inherit a RoR api, that provides that to a angular app. I am new to RoR and I am having difficulties with the way the api returns data in json.
def getLocations
location = params[:name]
query = "select * from view_locations where lower(location_name) like lower('#{location}%') limit 4 "
propAll = Property.connection.select_all(query)
respond_to do |format|
if !propAll.blank?
format.json { render json: {status:"ok", data:propAll}}
else
format.json { render json: {status:"error"}}
end
end
end
This code returns this array:
[{"location_name":"Nuevo León","id":"19","quantity":"5988","type":"State"},{"location_name":"Naucalpan de Juárez, México","id":"09","quantity":"131","type":"City"},{"location_name":"Nayarit","id":"18","quantity":"91","type":"State"},{"location_name":"Nacajuca, Tabasco","id":"013","quantity":"20","type":"City"}]
Is there any way that I could return the JSON instead of an array?
If its not possible, how should I use the returned array in Angularjs, right now we are going through every array element and pushing it in another array .
Thanks, for any help provided
Alberto
I have developed a rest api, in which I am using instance variable. there are two methods index and show, I have created a instance variable in index method which I want to use in show method on user request.
But i do not know, the instance variable is null in show method, I am sure that I am not initaializing the class anywhere explicitly. Code snippet is below
def index
data = Hash.new
#temp = DataHelper.filter(params)
if(params[:type] == 'Student')
json = DataStudenteHelper.sfilter(params, #temp)
else
json = EmpDataHelper.empfilter(params, #temp)
end
puts data.to_json
render :status => :ok, :json => json
end
def show
puts #temp.to_json // null here
if (params[:type] == 'Student')
#h = StudentHelpHelper.shfilter(params, #temp)
else
#h = EmpDataHelpHelper.emphfilter(params, #temp)
end
render :status => :ok, :json => #h
end
in the methods sfilter, empfilter, shfilter and emphfilter, I am just processing #temp but it is null in show method...
So any idea what is the issue thanks...
You seem to be assuming that a controller will persist across multiple requests so that you can initialize a variable in an index action and still be able to use it in a subsequent show action. This is not the case. Rails controller instances exist only for the duration of the request they serve. You cannot keep values in memory like this across requests (nor should you want to as that would require that requests be served in a particular order and would leak data between different users).
If you need to initialize this variable before all of your controller actions consider using a before filter. In your case this probably means that you also need to supply the data you need in the params of the show action.