简体   繁体   English

Rails路由具有多个模型ID

[英]Rails Routes with multiple model ids

I've got an app with an Item model and a Fixer model. 我有一个带有Item模型和Fixer模型的应用程序。 Each Item belongs to a Fixer, and Fixers can have many items. 每个物品都属于一个固定器,固定器可以有很多物品。 I want to create a "log" page where a particular fixer can update information on a particular Item associated with them. 我想创建一个“日志”页面,其中特定修复程序可以更新与其关联的特定项目的信息。 Ideally something like this 理想情况下是这样的

www.myappname.com/fixers/<fixer_id>/log/<item_id>

I'm fairly new to Rails, so I'm not really sure how to figure out the routing/controller for this one. 我对Rails相当新,所以我不确定如何弄清楚这个路由/控制器。 I looked in the Rails Guide section on routing, and the only thing that looked similar to what I want is Nested Models, but I ideally don't want to nest the models, because while items may technically "belong_to" fixers, that's not really the case in the real world (fixers are just associated, and belong_to was the most sensible way), and there's no other part of the relationship that requires/makes sense with nesting. 我查看了Rails指南中关于路由的部分,唯一看起来类似于我想要的是嵌套模型,但我理想情况下不想嵌套模型,因为虽然项目在技术上可能是“属于”修复者,但实际上并不是这样。在现实世界中的情况(固定器只是关联,并且belongs_to是最明智的方式),并且关系中没有其他部分需要/有意义的嵌套。 More importantly, I don't really get what nesting the models means or does, and I try to avoid implementing solutions that I don't fully understand. 更重要的是,我并没有真正了解模型的嵌套意味着什么,我试图避免实现我不完全理解的解决方案。

If nesting's the way to go, let me know, but otherwise, how might I go about routing this? 如果嵌套是要走的路,请告诉我,但除此之外,我该如何进行布线呢? I've tried this in my routes.rb file: 我在routes.rb文件中试过这个:

match 'fixers/:id/log/:id' => 'fixers#log'

and created log.html.erb, but I don't know how I'd select the params of that in a controller (how does it know which ":id" I'm selecting for? Is there a better way to do this? 并创建了log.html.erb,但我不知道如何在控制器中选择它的参数(它如何知道我选择哪个“:id”?有没有更好的方法来做到这一点?

Thanks! 谢谢!

Since they are associated with each other you may try to use the nested routing: 由于它们彼此关联,您可以尝试使用嵌套路由:

resources :fixers do
  resources :log
end

Nested resources are used for one to many relationships as you can read in Rails routing guide. 嵌套资源用于一对多关系,您可以在Rails路由指南中阅读。

You can name the params any way you see fit, it doesn't have to be :id . 你可以用任何你认为合适的方式命名params,它不一定是:id For example: 例如:

match 'fixers/:id/log/:item_id' => 'fixers#log'

and in your controller: 并在您的控制器中:

@fixer = Fixer.find(params[:id])
@item = Item.find(params[:item_id])

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

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