【问题标题】:Rails link_to pass :id from show to another controller actionRails link_to 将 :id 从 show 传递到另一个控制器操作
【发布时间】:2017-03-07 19:28:52
【问题描述】:

我正在 show.html.erb 中查看 1 个产品,下面有一个链接显示“查看该公司的其他产品”。这个 link_to 连接到同一控制器中的另一个非静态操作,该操作从数据库中检索同一公司的其他产品,如 show.html.erb 中所示。

link_to 可以将当前产品的 :id 传递给它正在渲染的操作吗?我是 Rails 新手,如果问题没有意义,请告诉我。我不确定是否也需要定义路线。谢谢。

products_controller.rb

def show
 @company_products = Product.by_company
end

show.html.erb

<%= link_to "View other products from this company", company_products_path(:anchor => "#{@company_products}") %>

routes.rb

get '/company_products_' => 'products#company_products'

【问题讨论】:

  • 你想要拥有 RESTFUL 路由还是保留你拥有的非 RESTFUL 路由?
  • 我不确定 RESTFUL 路由将如何工作。请建议
  • RESTFUL 路由按照 gwalshington 的建议工作,输入资源 :products。令人困惑的是,名称 show.html.erb 暗示您有 RESTful 路由(当您添加 RESTFUL 路由时,b/c Rails 会自动将其填充为潜在的 URL/操作),而您没有。你应该找到一个解释这个的教程,我真的无法在评论中正确解释它。它太长太复杂了。
  • 我建议 lynda.com 的教程:lynda.com/Ruby-Rails-tutorials/Ruby-Rails-5-Essential-Training/…。如果你愿意,你可以使用不同的,但我会先看看其他人如何构建他们的整个项目,然后尝试构建你自己的。这确实是学习 Rails 最快、最不令人沮丧的方式。祝你好运! :)
  • 哦不,我知道宁静的路线!我自己几乎完成了一个应用程序:-) 我的意思是我不明白 Restful 路线在“我的情况”中是如何工作的,因为你提到了 restful 和 non-restful 并且我使用了 non-restful。我只想根据条件显示几条记录(如索引)。show 已经显示 1 条记录。我如何将当前对象的 :id 从显示传递到索引或其他非休息操作。@gwalshington 给出的是休息路线。如何会创建非休息路线吗?我猜 link_to 无法解析路线,因此它根本不会像她建议的那样显示。

标签: ruby-on-rails link-to


【解决方案1】:

你想做这样的事情:

@company_products.each do |company|
  link_to "View other products from this company", products_path(company)
end

路线:

resources :products

【讨论】:

  • 你提到的是索引视图。我在节目中要求 link_to。所以无论如何我都有当前的产品。 link_to 通过传递 hash-product 或 product.id 根本不显示。也没有错误。任何建议。
【解决方案2】:

我最终通过将 show 中的 object 的 :id 通过 link_to 传递给 non-restful 操作来解决它。

如果#show 中的整个@company_products 可以按原样传递,我愿意接受建议,因为我首先要查找该公司是否有任何其他产品,如果有,则仅在link_to 和in 中传递一个ID controller#company 再次运行查询以获取要显示的所有产品的相同数据。所以两次运行相同的查询不是 DRY。

controller#show 与最初发布的保持一致。

routes.rb

resources :products do
  get :company, on: :member
end

show.html.erb

<%= link_to "View other products from #{@company_name}", company_product_path(@product.company_id) %>

控制器#company

def company
  @products_of_company = Product.where(company_id: params[:id])
end

现在在 company.html.erb 中,列表刚刚显示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多