【问题标题】:rails: link_to into another controller with paramsrails: link_to 到另一个带有参数的控制器
【发布时间】:2013-09-17 21:12:38
【问题描述】:

如何使 link_to 指向另一个控制器中的操作,包括参数。我有一系列引用产品 ID 的交易。我正在尝试将每个交易链接到它的产品。

控制器

def page
  @transactions = Transaction.all
end

页面(haml)

- @transactions.each do |x|
  = link_to "Product", {controller: "product", action: "show", id: x.product_id} 

错误

No route matches {:controller=>"product", :action=>"show", :id=>38}

rake 路线

product GET    /products/:id(.:format)     products#show

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您有语法问题:

    Product的控制器是ProductsController(注意是复数),所以你应该把这个hash传递给link_to:

    {controller: "products", action: "show", id: x.product_id}
                         ^
    

    还要确保x.product_id 存在,否则会引发错误“No routes matches { ... }”。


    编码风格的一个改进是使用路径助手生成的路径:

    link_to "Product", product_path(x.product_id)
    

    这个助手是通过你的 routes.rb 中的resources :products 生成的

    有关 Url Helpers 的更多信息:http://guides.rubyonrails.org/routing.html#path-and-url-helpers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      相关资源
      最近更新 更多