Back

Rails - JSON views

added on :: 15 June 2014
Rails has this awesomeness to render views- partials as JSON.

Say you like to click on the new form and render that form in the same page and inject the view code to the page.

#controller
  def new
@design = Design.new
render :json => {:form => render_to_string(:partial => 'form')}
end

Views
#index.html.erb
 

<%= notice %>



Listing Designs













<% @designs.each do |design| %>







<% end %>

Title Description
<%= design.title %> <%= design.description %> <%= link_to 'Show', design %> <%= link_to 'Edit', edit_design_path(design) %> <%= link_to 'Destroy', design, method: :delete, data: { confirm: 'Are you sure?' } %>





<%= link_to 'New Design', new_design_path , :id => "new-design"%>





<%=content_for :javascripts do%>




<%end%>


That is all. Here is a like to the source codeĀ  https://github.com/iamfree-com/json-in-views


You can do the similar with for JavaScript by rendering view with javascript and by adding

<%= link_to 'New Design', new_design_path ,  :remote => true %>

Then add new.js file in views/designs directory

$('#designform').html('<%= j render("designs/form",  :locals => { :hi => "hi"}%>');


Why would you need all these JavaScript frameworks when you have Rails:-)

Back