简体   繁体   中英

ruby on rails rendering json in js.erb

In a create method in controller I have the following code:

respond_to do |format|
  format.js { render json: { html: render_to_string(partial: '/users/photos/card', object: @photo, as: 'photo') } }
end

which works perfectly. Now I would like to move this in create.js.erb to have the possibility to execute additions js. However I do not figure out how to render the json above in create.js.erb.

Any idea how to accomplish this. Thanks in advance!

If I understood you right, what you are trying to achieve is to be able to access your JSON inside a js.erb view. In order to accomplish that, what I've done in the past is the following:

In your create.js.erb:

var yourJSON = JSON.parse("<%= raw(j render :partial => '/users/photos/card', object: @photo, as: 'photo') %>");

And in your controller:

respond_to do |format|
  format.js # This will render the create.js.erb
  format.json { render :partial => '/users/photos/card' } # Leave this one in case you also want to be able to respond to this format i.e: "http://localhost:3000/users/photos/card/id.json"
end

Hope this helps!

PS: Let me know if you were trying to achieve something different.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM