Can we pass additional parameters along with render method in rails - ruby-on-rails

Controller method:
def add
#project = Project.find(1)
render xml: #project #wish to pass one more variable like this here
end
ajax call :
endpoint = ROOT_PATH + '/projects/add/'+data_type;
$.ajax({
url : endpoint,
type : "get",
dataType : "xml",
success : function(xml) {
id = $(xml).find('id').text();
title = $(xml).find('title').text();
// wish to display the sent additional parameter here.
}
});
I am able to get project instance parameters 'id' and 'title' in the ajax call.But I wish to send one more parameter along with the #project and wish to use the value of this parameter inside the ajax call. Could some one help me out pls. Thanks!

One of the ways could be:
render xml: #patient.as_json.merge({:YOUR_KEY => YOUR_VALUE})
if you want to send the requested params or nil #patient then:
requested_params = params.except(:controller, :action)
render xml: #patient.present? ? #patient.as_json.merge(requested_params) : requested_params`

Related

Rendering template with json params

I have new and create actions like this:
def new
#foo = Foo.new
end
def create
#foo = Foo.new(foo_params)
respond_to do |format|
if #foo.save
format.html { redirect_to root_path }
else
format.html { render :new } //**this line I want to send params**
end
end
end
I have a jbuilder file to new action like this:
new.json.jbuilder
json.foo do
json.a "Some important info"
json.b "Some important info"
end
And rails can't read this file after create's validation fails. How to render a view template (like render :new) and send some json data in this view?
I have a js calling like this:
var json_url = window.location.href + ".json";
var foo;
$.ajax({
url: json_url,
dataType: 'json',
async: false,
success: function(data) {
foo = data.foo;
}
});
If you want Rails to render a file, you'll need to remove the call to redirect_to as it will effectively prevent any rendering.
Furthermore, if you don't want the controller to respond to different formats, it's better to skip the call to respond_to, too.
If you just call render action: :new, the view template will have access to all controller instance variables (like #foo):
json.foo do
json.a #foo.a
json.b #foo.b
end

Value not bind to the view from controller

I have two select tags as follow
<%= f.select(:floor_id, ProjectFloor.find(:all,:order => "name ASC",:conditions => ["project_id = ?", #project.id]).collect{|b|[b.name, b.id]}, {:include_blank => 'Select'}) %>
<%= f.select(:unit_id, #floor.collect{|b|[b.name, b.id]}, {:include_blank => 'Select'}) %>
When the user select the value on the first select tag called :floor_id then the value of the select tag data should be load to :unit_id select tag
I have try the following to read and fetch the data but. the floor_id always receiving null
My controller method is as follow :
#floor_id = params[:floor_id]
#project = Project.find(params[:project_id])
#proposed_customer = ProposedCustomer.new
#floor = ProjectFloorUnit.select_units(#project.id, #floor_id)
The select unit method is work fine for static values so it must work if we pass the proper param.
When a page is completely loaded, it disconnects from the server. So, you need to initiate a separate request, and the response of the request will change the values or whatever you want in the second dropdown.
You can use jQuery to send a new request:
$("#floorIDSelectTag").change(function() {
var floorID = $(this).val();
$.ajax({
type: '',
url: '',
// other things
success: function(data) {
// Here, you need to use the data from the request's response,
// and update the things in 2nd dropdown
}
});
});
What will be the URL that you will use in AJAX call? For it, you need to build a new route in config/routes.rb file, a new action in your controller, and send back the data in JSON format. Something like following:
def get_data_for_floor_id
#floor_id = params[:floor_id]
# Do the other stuff, and prepare the response you need to send.
respond_to do |format|
format.json { }
end
end

Rails Ajax Call : Pass JSON to separate controller method

Hey everyone I am having an issue setting up my app. It uses the shopify API and essentially what it does is grab some data via a view and sends it to the controller but I am having issues passing it to another method in the controller to use the API to save the data.
Here is my code :
Controller
class BuilderController < ShopifyApp::AuthenticatedController
def index
urlval = request.fullpath
#urlCheck = urlval.split('/').last
end
def show
url = request.fullpath
#urlID = url.split('/').last
#customers = ShopifyAPI::Customer.search(query: "id:"+ #urlID)
#need to get a way to retrieve the ajax call info here to pass into the update
end
def updateCustomer(notes)
#customers.each do |cus|
cus.note = notes
cus.save()
end
end
def new
notes = params[:notes]
updateCustomer(notes)
render json: notes
end
end
View
<button id="test">TEST</button>
<script>
var butt = document.getElementById('test');
butt.addEventListener("click",function(){
$.ajax({
url: "/builder/new",
type: "GET",
data: {
"notes": [
"test",
"test2"
]
},
success: function(data,text,xhr) {
console.log(text);
console.log(xhr);
console.log(data);
alert('successfully');
},
error: function(data,error){
console.log(data);
console.log(error);
alert("help");
}
});
});
</script>
Rather than a fully separate method, have you looked into the
respond_to method? http://api.rubyonrails.org/classes/ActionController/MimeResponds.html#method-i-respond_to
You could do (assuming html is the primary request type, change if it isn't):
def index
respond_to do |format|
format.html { actions }
format.json { actions }
end
end
This the method we use to accommodate different request types within the same action. Please let me know if I've misinterpreted your question.
you can use this
update_all(updates) public
Updates all records with details given if
they match a set of conditions supplied, limits and order can also be
supplied. This method constructs a single SQL UPDATE statement and
sends it straight to the database. It does not instantiate the
involved models and it does not trigger Active Record callbacks or
validations.
http://apidock.com/rails/v4.0.2/ActiveRecord/Relation/update_all
def new
notes = params[:notes]
#customer.update_all({note: notes})
respond_to do |format|
format.html {}
format.json { json: #customer.json }
end
end

adding extra data to ajax response

I have this piece of code:
var jqxhr = $.ajax({
url: "/customers/shipments/get_carrier_products_and_prices_for_shipment.json",
type: "POST",
dataType: "json",
data: data
})
and the last lines of controller:
if #carrier_products_and_prices.length > 0
#digest = params[:digest]
#html = render_to_string(partial: "components/customers/shipments/carrier_products_and_prices_for_shipment_table.html.haml", locals: {carrier_products_and_prices: #carrier_products_and_prices})
else
#html = render_to_string(partial: "components/customers/shipments/no_carrier_products_available.html.haml", locals: {carrier_products_and_prices: #carrier_products_and_prices})
end
Which hits a rails controller. My question is, how can I control/append extra data to the response object that rails returns? Right now, it only returns a html string, and I would like to also be able to send a response ID with it
It looks like your client is expecting a JSON body. Just create a hash of the values you want returned to the client and call render json: hash where hash contains the values you want to return to the client as JSON.
Since you're already using the JSON dataType, there's nothing stopping you from packing up your stuff in an object:
{
"html": "<div>...</div>",
"responseID": 69
}

Why is AJAX in Rails 3 so hard? Or, what am I doing wrong?

None of the tutorials I seem do what I'm trying to do. Very simply, I want a user to be able to submit a POST request to a controller (to "LIKE" a video) and have the controller respond back with a JSON object. Any help would be appreciated.
Thanks
EDIT Because SO is messing the formatting up, here is a gist of my code too:
https://gist.github.com/813503
Here is my controller:
class LikesController < ApplicationController
before_filter :get_ids
respond_to :json, :js
def videolink
results = {}
# check to see if the user has liked this videolink before
if current_user
liked = Like.video?(current_user, #vid_id)
results["status"] = "OK"
results["liked"] = liked
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
def update
results = {}
if current_user
results["status"] = "OK"
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
private
def get_ids
#vid_id = params[:videolink_id]
end
end
Here is my JS file:
$("#likeVideo").click(function() {
$.ajax({
contentType: "application/json",
data: { game_id: game_id, videolink_id: current_video["videolink"]["id"] },
dataType: "json",
type: "POST",
url: "/likes/" + game_id,
success: function(data) {
console.log("Success", data);
}
});
return false;
});
My routes:
resources :likes do
collection do
get "videolink"
end
member do
post :update
end
end
And here is the error I get:
NoMethodError
in LikesController#update
undefined method `{"status":"OK"}_url' for #<LikesController:0x0000010178be58>
If you want to send back custom JSON, Instead of respond_with(results.to_json)... just render the text
render :text=>results.to_json
The responds_with is a way for you to easily send back objects, with their location (url). So that's why your error is telling you that that '_url' is invalid.
More info on responds_with, courtesy of http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering
If another format was requested, (i.e.
:xml or :json)
If it was a GET request, invoke the :to_format method on the resource and
send that back
If the resource has validation errors, send back the errors in the
requested format with the
:unprocessable_entity status code
If it was a POST request, invoke the :to_format method on the resource
and send that back with the :created
status and the :location of the new
created resource
Else, send back the :ok response with no body

Resources