link_to问题

时间:2011-05-19 12:12:23

标签: ruby-on-rails ruby-on-rails-3

我想在link_to中显示产品计数,link_to是application.erb.html中部分显示的一部分,问题是,我在我的应用程序控制器中有一个名为products_on_cart的方法,它返回产品计数,当我尝试这段代码:

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

rails给我一个错误:

  

“语法错误,意外'&gt;'
  ... er =&gt;“carts”,:action =&gt;“index”%&gt;“

我真的不明白为什么,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:3)

您无法在<%= .. %>内使用<%= .. %>

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

答案 1 :(得分: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方法。

相关问题