简体   繁体   中英

Can you define multiple actions with the same name in Rails?

In asp.net MVC, you can define multiple action methods with the same name, as long as the arguments (the method signature in other words) is different. Can you do this in Rails, or do you have to settle with switch statements inside the same action?

No you can not define multiple actions with the same name.

It is independent of Rails, it's Ruby thing - the latter definition of the method will just override the former.

One of the solutions is to make method accept more arguments (some might be optional, for example) and differentiate based on these.

I'm guessing that by "action" you mean controller action. You don't have to put your logic in the controller. You can set up logic beforehand that generates a link or a path to two different controllers, both controllers having an action with the same name.

If you're wondering how method lookup works in Ruby: if you call a method on an object and there are multiple methods in that object's lookup chain with the same name, Ruby will use the one with the nearest scope. See "Ruby method lookup" for more details. Keep in mind you can always break out of that method lookup chain and call the specific "version" of the method that you want by naming the class, module, etc.

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