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
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.
If you want a clear explanation of redirect_to ... checkout
https://gist.github.com/jcasimir/1210155
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With