link_to与Rails中的块

时间:2013-12-19 19:31:00

标签: ruby-on-rails

我在此存储库中看到过此代码:

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

这实际上转换为以下HTML:

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

我想知道如何将一个块传递给link_to以使其工作?

2 个答案:

答案 0 :(得分:2)

我认为这就是你要找的东西。 “do..end”中的内容将放在标签内。

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

它应该产生

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

原始代码中发生的事情是表达式{ account.customer_id.to_s }作为块传递给link_to。如果您希望将客户ID与“login”和“company_name”一起显示,请将其放在块中。

答案 1 :(得分:0)

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

并在您的config / routes.rb中,在文件的开头添加

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