Hommer Smith
Hommer Smith

Reputation: 27852

link_to with block in Rails

I have seen this code in this repository:

<%= link_to(:controller => 'account', :action => 'select', :account_id => account.customer_id) { account.customer_id.to_s } %>
    (<%= account.login %> / <%= account.company_name %> )

This actually converts to the following HTML:

<a account_id="8282277272" action="select" controller="account">8282277272</a>
        ( loginname / companyname )

I am wondering how would you pass a block to link_to in order to make this work?

Upvotes: 3

Views: 825

Answers (2)

donleyp
donleyp

Reputation: 320

I think this is what you're looking for. The stuff inside the "do..end" will be put inside the a tag.

<%= link_to(:controller => 'account', :action => 'select', :account_id => account.customer_id) do %>
    (<%= account.login %> / <%= account.company_name %> )
<% end %>

It should produce

<a href="<path to controller with account_id parameter>">
    (username / Company, Inc.)
</a>

What was happening in your original code was that the expression { account.customer_id.to_s } was being passed as the block to link_to. If you want the customer id to be displayed along with the "login" and "company_name", put it inside the block.

Upvotes: 4

usha
usha

Reputation: 29349

   <%= link_to(account_select_path(:account_id => account.customer_id.to_s)) do%>
      <%= account.customer_id.to_s %>
   <%end%>   
   (<%= account.login %> / <%= account.company_name %> )

and in your config/routes.rb, in the beginning of the file, add

match 'account/select' => "account#select", :as => :account_select

Upvotes: 0

Related Questions