简体   繁体   中英

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? 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. 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.
  2. Use different id fields, and logic to see which one to update, eg lecture_id and speaker_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 . But when you use a scheme like you're asking for, all bets are off. /speaker/42 can end up .. anywhere in your application.

Also remember that one huge advantage of using Ruby on Rails is that essentially every RoR app more or less looks alike. 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. But this is most definitely not one of them ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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