Rails: link_to with block and GET parameters?

How can I get the query string and URL parameters in the declaration of the link_to block? Right now I have this one that works:

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

The above work and outputs:

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

I want to do something like this:

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

But above format outputs:

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

This is not what I'm looking for ... I want it to output the url, as in the previous example.

How can i achieve this?

+7
ruby-on-rails activerecord actionview
source share
4 answers

link_to accepts the same options as url_for . Having said that there is no :type option, and in fact it does not accept blocks, so I assume that the reason your second example works is because it is within the scope of the book. As Tom mentioned in the answer to this answer, passing a block to link_to can be used as a replacement for the first argument (link text).

If Book is a resource, you can get the link_to to create the URL you are looking for by passing it one of the convenient resource routes you automatically generate. Run rake routes before trying the following:

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

Otherwise, you can explicitly indicate to which controller / action you want to bind:

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

Happy hack.

EDIT: Almost forgot, you can add query strings to bypass them after you declare the identifier of the object you are referencing.

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

Will the product be /books/1/edit?query1=value&query2=value . As an alternative:

 <%= link_to "Edit", :controller => "books", :action => "edit", :id => book, :query1 => "value", :query2 => "value" %> 
+13
source share

Try Follwing

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

or to reach the same URL Use

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

Ruby does not know whether the do ... end block sends to link_to or book , and sends it to book because it is closer to the block. book do ... end returns nil , so you are left with link_to :edit, :type=>'book', :id=>nil . You will need to copy the parameters, and while you are on it, I would rewrite it to be more understandable using the controller, action and setting id: link_to{:controller=>"books",:action=>"edit",:id=>book}do ... end

0
source share

in the mime_types.rb file add:

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

0
source share

All Articles