views:

730

answers:

4

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?

A: 

Try Follwing

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

or to achieve same url Use

<% link_to(:action=>'edit', :type => 'book', :id => book) do %>
    ...
<% end %>
Salil
+2  A: 

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" %>
Damien Wilson
The block seems to be a way of capturing input to place within the `<a>tags</a>`. http://railsapi.com/doc/rails-v2.3.5/classes/ActionView/Helpers/UrlHelper.html#M002452
Tim Snowhite
A: 

Ruby doesn't know if you're sending the do ... end block to link_to or book, and is sending it to book because it is closer to the block. book do ... end returns nil, so you're left with link_to :edit, :type=>'book', :id=>nil. You will need to bracket the parameters, and while you're at it, I would rewrite it to be more understandable with a controller, action, id setup: link_to{:controller=>"books",:action=>"edit",:id=>book}do ... end

Ryan
A: 

in mime_types.rb file add:

Mime::Type.register "text/application", :book

Sandy XU
add a type for request
Sandy XU