Because the action is “remove_from_cart” (see params[:action]), and that’s what Rails uses to find the view to use. Do this:
class SomeController < ApplicationController
def remove_from_cart
if quantity <= 0
empty_cart
render :partial => “empty_cart”
else
foo
end
end
Jason
Sorry, hit Send too quickly.
You can also do, instead of the above :
def empty_cart
render :partial => “empty_cart”
end
as long as there is no render call in remove_from_cart. Otherwise you’ll get an error along the lines of “can’t render more than once”.
Jason
Ah, if you do :partial => “empty_cart”, then the file Rails looks for is _empty_cart.rjs (note the beginning underscore).
Can you just do render “empty_cart” ?
Jason
Sorry, but that’s not how Rails works. It doesn’t figure out the view from the function being ran, but from the request from the client. E.g.
www.host.com/users/login
becomes:
params = {
:controller => “users”,
:action => “login”
}
And thus, if there is no explicit render call in UsersController#login, then Rails looks for login.rhtml / login.rxml / login.rjs
What you can do is an explicit render call as such:
class SomeController < ApplicationController
def remove_from_cart
if quantity <= 0
render :action => “empty_cart”
else
foo
end
end
def empty_cart
does_something_here
end
end
But that only tells Rails what view to look for, it doesn’t actually call SomeController#empty_cart, so the “does_something_here” won’t actually get done, but you will get “empty_cart.rhtml” to render.
From what I’ve gathered from your code and responses, I would say this is your best bet:
class SomeController < ApplicationController
def remove_from_cart
if quantity <= 0
empty_cart
render :partial => “empty_cart”
else
foo
end
end
def empty_cart
does_something_here
end
end
and then have a view file under views/some_controller/_empty_cart.rjs.
Hope that helps.
Jason
What about:
def empty_cart
session[:cart] = nil
render :partial => “empty_cart”
end
then you just need _empty_cart.rjs and can get rid of empty_cart.rjs.
You do make a lot of view files when you start dealing with AJAX and RJS, it’s just how Rails is. But you can call any view file from any controller through the #render method.
It’s also possible to run RJS code in your controller, like so:
def empty_cart
session[:cart] = nil
render_update do |page|
page.visual_effect :puff
end
end
but I’m not a fan of this as it starts to muddle the line between View and Controller.
Jason