Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - redirect_to

I'm having some trouble understanding the redirect_to statement. I have a model "Book" (with an boolean attribute "read")and a controller "books". Now I created a second controller "Admins" having to methods: index and change. The index view just renders a list off all Books with a link to the change method:

<% @Books.each do |d| %>
<%= d.title %><br>
<% if d.read==true %>
<%= link_to "mark unread", change_path(:id=>d.id)%>
<% else %>
<%= link_to "mark read", change_path(:id=>d.id)%>
<%end %>

Now the change method just changes the "read" attribute:

@book=Book.find(params[:id])
if @book.read==true
@book.update_attributes(:read => false)
else
@book.update_attributes(:read => true)
end
redirect_to action: "index"

The Problem is: rails tries to redirect me to the show action using the :id as a parameter...(perhaps because the change_url is /admins/change?id=3) But I just want to be directed back to the index view "/admins"

is there a way? it seems like rails always tries to redirect to the view action if there is an id as a parameter

Thanks alot

PS: the routes.rb contains resources:admins and resources:books

like image 475
Sven Avatar asked Apr 06 '14 15:04

Sven


3 Answers

Use this

redirect_to :controller => 'admins', :action => 'index'

Or

redirect_to admins_url

The above two will direct you to the index page of AdminsController. There is no way that Rails would route it to show action UNLESS you are redirecting to show action from the index action of AdminsController. Since, you did not share index action code of AdminsController, I would recommend you to check there.

like image 199
Kirti Thorat Avatar answered Oct 21 '22 06:10

Kirti Thorat


If you want a clear explanation of redirect_to ... checkout

https://gist.github.com/jcasimir/1210155

like image 30
Ryan-Neal Mes Avatar answered Oct 21 '22 05:10

Ryan-Neal Mes


I had a kind of similar issue some days ago. I would suggest to do this within the form where you list the books and the mark/unmark checkboxes.

<%= form_for @book,:url => book_index_path do |f| %>

This worked fine for me, when I set up a site where you create data and the user is immediately redirected to the same page (incl. success/error message).. to do a kind of human batch-processing.

like image 42
frankfurt-laravel Avatar answered Oct 21 '22 05:10

frankfurt-laravel