I’m trying to refactor some legacy code at the moment. It currently goes something like this:
Controller
def create
# do stuff
respond_to do |format|
format.html { do stuff }
format.js { render partial: 'stage_two', locals: { some instance variables } }
end
end
Then in the views/controller_name/_stage_two.js.erb there is:
$('.some_element').children().fadeOut( function() {
$('.some_element').children().remove();
$('.some_element').html("<%=j render partial: 'form', locals: { stuff } %>");
$('.some_element .stage_two').fadeIn();
});
So basically the controller action is essentially rendering javascript. And that particular javascript is just removing an element from the page, changing the contents, then fading it back in. Is there a better way to do this? I know typically javascript lies in the app/assets/javascripts.
Your current implementation is quite DRY already and standard way.
The html request should also render the same partial but with layout.
The js request should render js response(rendering partial) and update the portion of page.
Those are your assets, this
stage_two.js.erbis not essentialy your assets file, this is instead your action handling for the js response.Definitely for smaller update actions you can use json request and receive json response to update view, but for many of the cases(esp. when dealing with large data) that fails, and your current implementation is fine in that…