In my app, I've got a little box that appears on every page, checking on the status of requests made by the user. If a request is accepted at any time, then the user should automatically be taken to a certain page. This is my code so far:
<% offersMade.each do |w| %>
<% if w.accepted == true %>
<% redirect_to offer_path(:email => "email@gmail.com") %>
<% end %>
<% end %>
But I'm getting this error:
undefined method `redirect_to' for #<ActionView::Base:0x1042a9770>
Is it not possible to user redirect_to in a view? If not, is there something else I can use? Thanks for reading.
The code in the view could be moved into the controller which would make redirect_to available.
If the OP wanted to immediately change the URL when an offer is accepted then none of the Ruby code shown in the answers would help because it is only evaluated when the page is loaded. The OP would need to setup some kind of polling or push strategy to alert the browser when an offer has been accepted and then use the JavaScript redirect scheme posted in another answer:
Although, this does not answer the question: "How can I use redirect_to in a view", I think this answer would ultimately have been more useful to the OP. I stumbled across someone using this answer to redirect to another page, when the redirect should have been performed in the controller.
redirect_to is a method of ActionController::Base Class so you can not use it in ActionView.
You can try following
Edited for the email parameter
Sorry i don't know if there is anything in ruby for that.
redirect_to
is not a method ofActionView
. Its a method ofActionController
. You can probably use Javascript window.location.href on page load or some other event to take your user to another page.Yes, you can call
controller.redirect_to
from your view to get what you want without having to render the whole response and then use javascript on the client to make a new request.In your example, this would look like:
Note that this
controller.redirect_to
will not break out of your loop, so you will probably want tobreak
, and you'll probably want to make sure that the rest of your view is only conditionally rendered if you didn't redirect.(Disclaimer: I don't necessarily condone this technique. You would be better off doing this in your controller or helper, as others have mentioned.)
If you want to use redirect_to from view , do this method:
syntax : <%controller.redirect_to path %>
Example:<% controller.redirect_to users_profile_path %>