Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails passing params to new action

I linked to a new-action giving a param in the URL. That param should be readable in the create-action so that i can put it in the new created object.

Specific: I'm on the show-page of a bookshelf. there is a link_to linked to the new-action of book with a paramter containing the id of the bookshelf. When creating the book i want to put the id of the bookshelf into the foreign key of the book (bookshelf_id).

How do i do this the rails way? The link_to looks like this: link_to new_book_path(:bookshelf => bookshelf). I tried reading and passing the param with @book.bookshelf = Bookshelf.find(params[:bookshelf]) in the create-action but it was an empty string.

like image 937
user3509806 Avatar asked Dec 18 '22 18:12

user3509806


1 Answers

Post the relationships. If you're on the bookshelf show page you have access to that instance of bookshelf

<%= link_to new_book_path(:bookshelf_id => params[:id]) %>

When you click that link your url should have ?bookshelf_id=123 (or whatever)

Then, to access that param from the new page, you can either do this in your form (assuming it's a conventional rails form):

<%= f.hidden_field :bookshelf_id, value: params['bookshelf_id'] %>

If you take this approach you don't have to do anything additional. Just pass the params as you normally would.

If you'd rather you can access this param in your controller:

bookshelf_id = params['bookshelf_id']

You can set it there and then add it to the object you're creating.

like image 156
toddmetheny Avatar answered Dec 25 '22 11:12

toddmetheny