Using remote:true
on a form, or something, and responding from the controller with :js
, we can tell rails to execute some javascript file.
If you're destroying a user, for example. You'd have the User controller, and the Destroy action. You'd then have a file views/users/destroy.js.erb
with something along the lines of:
$("ul#users").html("<%= j render partial: 'user_list' %>");
My question is... Is there a shortcut to just put that javascript in the controller, so that I don't have to have these tiny files littered about my app? If I'm only rendering a partial with some instance variables, and nothing else, I'd like to see something like:
respond_with render :js, with: 'partial_foo', on: '#selector .bar'
Is there such a shortcut?
The only shortcut
I could recommend for you is to use json
and handle the response with your unobtrusive JS:
#view
<%= form_for @variable, remote: :true, method: :json %>
#controller
respond_to :json, :html
def action
respond_with @variable
end
JSON sends small serialized data objects, meaning you won't have to handle any files, and can handle the data as required:
#app/assets/javascripts/application.js
$(element).on("ajax:success", function(data) {
message = JSON.stringify(data);
alert(message.attribute);
});
If you like this idea, I can come back with some ideas for handling the partial