简体   繁体   English

在 ruby​​ on rails 中,我可以在一个控制器中添加多个资源吗?

[英]In ruby on rails, can I add more than one resources in one controller?

In the ruby on rails,can I add more than one resources in one controller?在 ruby​​ on rails 中,我可以在一个控制器中添加多个资源吗? Because, if i add more than one resources in one controller, there would be more than one Create, Update, index.. action and html.erb file in one views files.因为,如果我在一个控制器中添加多个资源,那么一个视图文件中就会有多个创建、更新、索引..动作和 html.erb 文件。 So what should I do If I wanna set more than one resources in one controller?如果我想在一个控制器中设置多个资源,我该怎么办? And how about those same name action can be exist successfully in one file?那些同名动作如何成功存在于一个文件中?

Can you do this?你能做这个吗? Sure.当然。 You can either:您可以:

  1. Use a postfix/prefix on the method names: update_lecture , update_speaker , etc.在方法名称上使用后缀/前缀: update_lectureupdate_speaker等。
  2. Use different id fields, and logic to see which one to update, eg lecture_id and speaker_id .使用不同的ID字段和逻辑,看看哪一个更新,如lecture_idspeaker_id

But ... do you want to do this?但是……你想这样做吗? NO !

Just think about the logic, a bit simplified, by default it's:想想逻辑,稍微简化一下,默认情况下它是:

[controller one] -> [model one]
[controller two] -> [model two]
[..etc..]

But now it becomes:但现在变成了:

                   /-> [model one]
[controller one] --
                   \-> [model two]

And eventually it'll become:最终它会变成:

                   /-> [model one]
[controller one] --
                   \-> [model two]


                  /-> [model three]
[controller two] ---> [model four]
                  \-> [model five]


                                          /-> [model six]
[controller three which was added later] -
                                          \-> [model three again because oops I forgot
                                               that it was already in controller two]

There is a simple to understand obvious mapping from a controller to an underlying model.从控制器到底层模型有一个简单易懂的明显映射。 This is good!这很好! It makes it easy to understand what methods and classes are involved when you have an URL like /speaker/42 .当你有一个像/speaker/42这样的 URL 时,它可以很容易地理解所涉及的方法和类。 But when you use a scheme like you're asking for, all bets are off.但是当你使用你所要求的方案时,所有的赌注都没有了。 /speaker/42 can end up .. anywhere in your application. /speaker/42可以在你的应用程序的任何地方结束。

Also remember that one huge advantage of using Ruby on Rails is that essentially every RoR app more or less looks alike.还请记住,使用 Ruby on Rails 的一个巨大优势是,基本上每个 RoR 应用程序或多或少都相似。 This is brilliant, because if my coworker is on holiday, I can fire up "his" application that I've never even seen before and fix that critical bug the customer just called in!这太棒了,因为如果我的同事在度假,我可以启动我以前从未见过的“他的”应用程序,并修复客户刚刚调用的那个关键错误!

There are some good reasons for doing unidiomatic stuff in RoR.在 RoR 中做单一的东西有一些很好的理由。 But this is most definitely not one of them ;-)但这绝对不是其中之一;-)

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

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