繁体   English   中英

Rails link_to将:id从show传递到另一个控制器动作

[英]Rails link_to pass :id from show to another controller action

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

link_是否可以在演示中传递当前产品的: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'

您想做这样的事情:

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

路线:

resources :products

最后,我通过将link_to中的show对象的:id传递给了一个非静态动作来解决了这个问题。

我愿意接受是否可以通过#show中整个@company_products的建议,因为我首先要查找该公司是否还有其他产品,如果有,仅在link_to和controller#company中传递一个ID再次运行查询以获取要显示的所有产品的相同数据。 因此两次运行同一查询不是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) %>

控制器#公司

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM