Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: link_to with block and GET params?

How can I achieve query string and URL parameters in a link_to block declaration? Right now, I have this, which works:

<%= link_to 'Edit', :edit, :type => 'book', :id => book %>

The above works, and outputs:

http://localhost:3000/books/edit/1?type=book

What I want to do is something like this:

<% link_to :edit, :type => 'book', :id => book do %>
    ...
<% end %>

But the above format outputs:

http://localhost:3000/books/edit/

Which isn't what I'm looking for... I want it to output a URL like the previous example.

How can I achieve this?

like image 592
ground5hark Avatar asked Apr 26 '10 05:04

ground5hark


1 Answers

link_to takes the same options that url_for does. Having said that, there is no :type option and it doesn't really accept blocks, so my guess is that the reason the your second example works is because it's located within the scope of a Book view. As mentioned by Tom in a reply to this answer, passing a block to link_to can be used as a replacement for the first argument (the link text).

If Book is a resource, you can get the link_to helper to generate the URL you're looking for by passing it one of the handy, automatically generated resource routes rails makes for you. Run rake routes before you try this:

<%= link_to "Edit", edit_book_path(book) %>

Otherwise, you can explicitly state what controller/action you want to link to:

<%= link_to "Edit", :controller => "books", :action => "edit", :id => book %>

Happy hacking.

EDIT: Almost forgot, you CAN add query strings bypassing them in AFTER you declare the id of the object you're linking to.

<%= link_to "Edit", edit_book_path(book, :query1 => "value", :query2 => "value")

Would product /books/1/edit?query1=value&query2=value. Alternatively:

<%= link_to "Edit", :controller => "books", :action => "edit", :id => book, :query1 => "value", :query2 => "value" %>
like image 62
Damien Wilson Avatar answered Sep 28 '22 19:09

Damien Wilson