Rails: generating URLs for actions in JSON response
Posted
by
Chris Butler
on Stack Overflow
See other posts from Stack Overflow
or by Chris Butler
Published on 2011-01-17T16:50:27Z
Indexed on
2011/01/17
16:53 UTC
Read the original article
Hit count: 273
ruby-on-rails
|JSON
In a view I am generating an HTML canvas of figures based on model data in an app. In the view I am preloading JSON model data in the page like this (to avoid an initial request back):
<script type="text/javascript" charset="utf-8">
<% ActiveRecord::Base.include_root_in_json = false -%>
var objects = <%= @objects.to_json(:include => :other_objects) %>;
...
Based on mouse (or touch) interaction I want to redirect to other parts of my app that are model specific (such as view, edit, delete, etc.).
Rather than hard code the URLs in my JavaScript I want to generate them from Rails (which means it always adapts the latest routes).
It seems like I have one of three options:
- Add an empty attr to the model that the controller fills in with the appropriate URL (we don't want to use routes in the model) before the JSON is generated
- Generate custom JSON where I add the different URLs manually
- Generate the URL as a template from Rails and replace the IDs in JavaScript as appropriate
I am starting to lean towards #1 for ease of implementation and maintainability.
Are there any other options that I am missing? Is #1 not the best?
Thanks!
Chris
© Stack Overflow or respective owner