Reputation: 3702
I am confused about how to use json in my rails (2.3.5) app. These are the elements that I need:
json data, calculated using helper methods (rails and my own ones), is quite big and it doesn't change often (in general it's footer, header and some other parts of the page), so it should be cached. What is the right way to do it?
I tried 3 approaches.
A.
- html template and javascript to render data placed in the view html.erb
- method to get json data placed in the helper
<script type="text/javascript">
var data= <%= helper_method %>;
</script>
Problem: how to cache json data?
B.
- html template and javascript to render data placed in the view html.erb
- method to get json data is a controller action
def footer
expires_in(4.hours)
render :json => { calculated_data }
end
- ajax request in javascript
$.ajax({
type: "GET",
url: "<%=footer_path %>",
success: function(data){
render json data in html template
}
});
Problem: second request send to the server...
C.
- html template and javascript to render data placed in the view html.erb
- method to get json data is a controller action
def footer
expires_in(4.hours)
render :json => { calculated_data }
end
- data in javascript
<script type="text/javascript" src="<%=footer_path %>">
</script>
Problems: how can I pass result of that script to a variable which I can use in the javascript that renders data in the template?
In case of B and C there is a need to include helpers in the controller (methods for calculating json data), which is quite ugly solution.
What should be the correct solution for this? Which approach is appropiate for this needs?
Thanks for all suggestions.
Upvotes: 9
Views: 5906
Reputation: 3702
No responses, but I found a solution. For those who could have similar problem, maybe it will save time for somebody...
I used approach A and Rails cache. I have a method in helper
def footer
return Rails.cache.fetch('footer', :expires_in => 4.hours){
caluclate_data_with_other_methods.to_json
}
end
Just this...
Upvotes: 29