This is how I generate XML for purchase model:
# GET /purchases/1
def show
#purchase = Purchase.find(params[:id])
#purchases = Purchase.all
respond_to do |format|
format.html # show.html.erb
format.xml { render :action => "something.xml.builder", :layout => false }
end
end
Now I'd like to get this rendered XML as string into variable so I could post it to WebService.
How can I get XML through sales_invoice.xml.builder without rendering it?
I don't want use dirty hacks and loading XML from http://appurl/purchases/1.xml
Thanks!
What I was looking for was render_to_string method.
Related
I basically have an action that because of logic needs to return with the contents of another js file. How do I go about doing this? Thanks
app/controllers/classrooms_controller.rb
def create
if params[:test_logic]
respond_to do |format|
format.js { render 'create_differently' } # This doesn't work.
end
else
redirect_to root_path
end
end
app/views/classrooms/create_differently.js.erb
alert('hi')
You need to add
:layout => false
to avoid the rendering of the html layout for your js file.
Additionally you could define the different js-file like this
:template => "classrooms/create_differently.js.erb"
both together:
format.js {
render :template => "classrooms/create_differently.js.erb",
:layout => false
}
For browser-based testing, please be aware calling js not html!
I am an experienced JAVA and C++ developer and I am trying to understand how rails works.
I got this code below:
respond_to do |format|
if #line_item.save
format.html { redirect_to store_url }
format.js { render :json => #line_item, :mime_type => Mime::Type.lookup('application/json'),
:callback => 'javascriptFunction' }
and I've been searching the api that defines what I can pass inside the format.js {} but I could not find..
first of all: what kind of statement is format.js, is that a variable?
and most important: what attributes can I pass into format.js {} ? can you pass the direct link? I've searched over the http://api.rubyonrails.org/
respond_to do |format|
format.js # actually means: if the client ask for js -> return file.js
end
js here specifies a mime-type that the controller method would send back as a response;
Default Rails mime-types.
If you try also with format.yaml:
respond_to do |format|
format.js
format.yaml
end
that will mean that your controller will return yml or js depending on what the client-side is asking;
{} in terms of ruby is a block;
If you don't specify any rails will try to render a default file from app/views/[contoller name]/[controller method name].[html/js/...]
# app/controllers/some_controller.rb
def hello
respond_to do |format|
format.js
end
end
will look for /app/views/some/hello.js.erb; // at least in Rails v. 2.3.
If you do specify block:
respond_to do |format|
# that will mean to send a javascript code to client-side;
format.js { render
# raw javascript to be executed on client-side
"alert('Hello Rails');",
# send HTTP response code on header
:status => 404, # page not found
# load /app/views/your-controller/different_action.js.erb
:action => "different_action",
# send json file with #line_item variable as json
:json => #line_item,
:file => filename,
:text => "OK",
# the :location option to set the HTTP Location header
:location => path_to_controller_method_url(argument)
}
end
I believe this was the url you were looking for:
https://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to
This might also be helpful to some, to see that you can actually render js directly within the format.js method, if you for example only have a small one line js statement you want to return, and you don't want to defer to a RJS file like controller_action_name.js.erb:
respond_to do |format|
format.html { redirect_to new_admin_session_path }
format.js { render :js => "window.location='#{ new_admin_session_path }'" }
end
Typical usage is:
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
And now I want to also pass a string named "teststring".
I've seen reference to using
:local => {:users => #users, :another => #another}
But I don't know how to merge the two together. I just haven't seen everything all together. Not much documentation to really explain the :xml in that line. And I don't know if I can deal with the string with :teststring => teststring?
And lastly, how do I deal with them in my index.html.erb now that I have multiple variables? Do they get passed with the same name from the render command?
Thanks.
If you want to render custom XML, you'll need to create a index.xml.erb file in the corresponding view directory for the controller. It works just like any HTML template you'd use, then:
app/controllers/home_controller.rb:
def index
#users = ...
#another = "Hello world!"
# this `respond_to` block isn't necessary in this case -
# Rails will detect the index.xml.erb file and render it
# automatically for requests for XML
respond_to do |format|
format.html # index.html.erb
format.xml # index.xml.erb
end
end
app/views/home/index.xml.erb:
<?xml version="1.0" encoding="UTF-8"?>
<document>
<%= #users.to_xml # serialize the #users variable %>
<extra_string><%= #another %></extra_string>
</document>
(You can read about ActiveRecord's to_xml method here.)
I am experimenting with Rails and was wondering what's needed to allow/add support for JSON requests?
I have a vanilla installation of Rails 2.3.5 and the default scaffolding seem to provide support for HTML & XML requests but not JSON.
class EventsController < ApplicationController
# GET /events
# GET /events.xml
def index
#events = Event.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #events }
end
end
# GET /events/1
# GET /events/1.xml
def show
#event = Event.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #event }
end
end
...
I'm new to this but it would appear as though i would need to add a format line in each method along the lines of:
format.js { render :js => #event.json }
couldn't this be done automatically? perhaps there's a template somewhere i need to update...or a flag i can set? Or perhaps, and most likely, I've missed the boat entirely?!?
You do:
format.json {render :json=>#event}
That will render the default activerecord JSON for the model
The option of ease of use is that you can write a private method which takes the format object and an object to render and then, based on the format, renders different things. Example:
class MyController<ApplicationController
def show
#event=Event.find(params[:id])
respond_to do {|format| myRenderer(format,#event)}
end
...
private
def myRenderer(fmt,obj)
fmt.json {render :json=>obj}
fmt.html
fmt.xml {render :xml=>obj}
end
I have an ActiveRecord model that I would like to convert to xml, but I do not want all the properties rendered in xml. Is there a parameter I can pass into the render method to keep a property from being rendered in xml?
Below is an example of what I am talking about.
def show
#person = Person.find(params[:id])
respond_to do |format|
format.xml { render :xml => #person }
end
end
produces the following xml
<person>
<name>Paul</name>
<age>25</age>
<phone>555.555.5555</phone>
</person>
However, I do not want the phone property to be shown. Is there some parameter in the render method that excludes properties from being rendered in xml? Kind of like the following example
def show
#person = Person.find(params[:id])
respond_to do |format|
format.xml { render :xml => #person, :exclude_attribute => :phone }
end
end
which would render the following xml
<person>
<name>Paul</name>
<age>25</age>
</person>
You can pass an array of model attribute names to the :only and :except options, so for your example it would be:
def show
#person = Person.find(params[:id])
respond_to do |format|
format.xml { render :text => #person.to_xml, :except => [:phone] }
end
end
to_xml documentation
I just was wondering this same thing, I made the change at the model level so I wouldn't have to do it in the controller, just another option if you are interested.
model
class Person < ActiveRecord::Base
def to_xml
super(:except => [:phone])
end
def to_json
super(:except => [:phone])
end
end
controller
class PeopleController < ApplicationController
# GET /people
# GET /people.xml
def index
#people = Person.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #people }
format.json { render :json => #people }
end
end
end
I set one of them up for json and xml on every object, kinda convenient when I want to filter things out of every alternative formatted response. The cool thing about this method is that even when you get a collection back, it will call this method and return the filtered results.
The "render :xml" did not work, but the to_xml did work. Below is an example
def show
#person = Person.find(params[:id])
respond_to do |format|
format.xml { render :text => #person.to_xml(:except => [:phone]) }
end
end
The except is good, but you have to remember to put it everywhere. If you're putting this in a controller, every method needs to have an except clause. I overwrite the serializable_hash method in my models to exclude what I don't want to show up. This has the benefits of not having t put it every place you're going to return as well as also applying to JSON responses.