简体   繁体   English

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

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

I'm viewing 1 product in show.html.erb and there's a link below that says "View other products from this company". 我正在show.html.erb中查看1个产品,并且下面有一个链接,显示“查看该公司的其他产品”。 This link_to connects to another non-restful action in same controller which retrieves from DB other products of same company as was shown in show.html.erb. 此link_to连接到同一控制器中的另一个非静态动作,该动作从DB检索同一公司的其他产品,如show.html.erb中所示。

Can link_to pass the :id of the current product in show to action it's rendering? link_是否可以在演示中传递当前产品的:id以使其呈现? I'm new to rails and please let me know if question is not making sense. 我是Rails的新手,如果问题没有道理,请告诉我。 I'm not sure if routes need to be defined as well. 我不确定是否也需要定义路由。 Thanks. 谢谢。

products_controller.rb products_controller.rb

def show
 @company_products = Product.by_company
end

show.html.erb show.html.erb

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

routes.rb 的routes.rb

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

You want to do something like this: 您想做这样的事情:

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

routes: 路线:

resources :products

I finally resolved it by passing the :id of object in show via link_to to a non-restful action. 最后,我通过将link_to中的show对象的:id传递给了一个非静态动作来解决了这个问题。

I'm open to suggestions if entire @company_products in #show can be passed as it is because I'm first finding if there are any other products for that company and if there are, passing an id only in link_to and in controller#company again running a query to get same data of all products to display. 我愿意接受是否可以通过#show中整个@company_products的建议,因为我首先要查找该公司是否还有其他产品,如果有,仅在link_to和controller#company中传递一个ID再次运行查询以获取要显示的所有产品的相同数据。 so running same query twice is not DRY. 因此两次运行同一查询不是DRY。

controller#show remains the same as originally posted. controller#show保持与最初发布的相同。

routes.rb 的routes.rb

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

show.html.erb show.html.erb

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

controller#company 控制器#公司

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

Now in company.html.erb, the list is just displayed. 现在在company.html.erb中,仅显示列表。

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

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