How can pass multiple parameters using respond_to
in rails? When I have more than 1 instance variable, I get an error. But I have an scenario when I have to pass in multiple parameters( instance variables
) thru respond_to
respond_to actually is supposed to only return a singular thing. The HTML template renderer is also only returning one thing - but embedding your multiple instance variables into it's HTML.
So you basically have to do the same for Json and XML: Construct a single object that contains all your data.
An example would be this code:
def show
@post = Post.first
@users = Users.where(:active => true)
respond_to do |format|
format.html #this will simply render the view
format.json { render :json => { :post => @post, :users => @users } }
end
end
Once you want to output these multiple values through Json you have to define a singular Json object that contains what you want to return.
In my example this is a Json object that contains post and users - thus giving the caller the same information as you give the HTML view.
The resulting Json looks like this:
{
post: {..},
users: [..]
}
Update :
If you are using this to render javascript where you have a script.js.erb you don't have to pass anything to the responds_to call but rather can use all instance variables (prefixed by a @) inside your js.erb file like you would in a normal HTML view by using the <%= %> syntax.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.