2011-05-19 66 views
0

我想在link_to中顯示產品數量,link_to是application.erb.html中部分顯示的一部分,問題是,我的應用控制器中有一個名爲products_on_cart的方法,它返回products count,when我試試這個代碼:link_to問題

<%= link_to "<%= products_on_cart%>", :controller=>"carts", :action=>"index"%> 

軌給我一個錯誤:

"syntax error, unexpected '>'
...er=>"carts", :action=>"index"%>"

我真的不明白,爲什麼有人可以幫助我嗎?

回答

3

您不能在<%= .. %>內使用<%= .. %>

<%= link_to products_on_cart, [:carts] %> 
+0

出現另一個問題,現在軌道看不到我的products_on_cart方法是在應用控制器 – Maki 2011-05-19 12:25:00

+2

在ApplicationController中: 是helper_method:products_on_cart – vicvega 2011-05-19 12:27:59

+0

現在的作品,非常感謝 – Maki 2011-05-19 12:30:46

3

您嵌套ERb標籤。確保products_on_cart()可以作爲一個輔助方法,然後重寫你的link_to代碼,而嵌套ERb的標籤如下:

<%= link_to products_on_cart(), :controller => "carts", :action => "index" %> 

爲了products_on_cart()一個輔助方法,無論是將其移動到app/helpers/application.rb,或聲明它作爲一個輔助你控制器:

def products_on_cart() 
    # method definition goes here 
end 

helper_method :products_on_cart 

如果你只需要在你的控制器訪問來自您的看法products_on_cart,而不是,把它在app/helpers/application.rb是要走的首選方式。如果您需要在控制器和視圖中使用它,請使用上面的helper_method方法。