Rails,一个控制器中的多个创建方法?

发布于 2024-12-21 16:26:22 字数 140 浏览 1 评论 0原文

我需要在一个控制器中有两种(甚至更多)不同的创建(和更新)方法。我已经有显示表单的视图,所以我基本上只需要告诉提交在控制器中调用哪个方法。这可能吗?如果是这样,怎么办?或者我可以只有一个创建方法,并让该方法根据调用该方法的视图执行不同的操作吗?

谢谢

I need to have two (or maybe even more) different create (and update) methods in one controller. I already have views displaying the forms, so I basicaly only need to tell the submit which method to call in the controller. Is that possible? If so, how? Or can I only have one create method and have that method do different things depending on which view called the method?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

波浪屿的海角声 2024-12-28 16:26:22

忽略这听起来是一个非常糟糕的想法这一事实,这是可能的。您将需要添加更多与控制器中的新操作相匹配的路由。您将无法调用它们“创建”和“更新”,因为方法名称在同一类中必须是唯一的。

话虽如此,我真的恳请您重新考虑一下您的方法。 REST,如 Rails 入门指南中所述,是迄今为止构建 Rails 应用程序的标准。如果您不熟悉它,我建议您停下来阅读它。您的应用程序将更容易构建和维护,并且您不会浪费时间询问结构问题。如果您熟悉它并选择忽略它,那么我祝您好运。

Ignoring the fact that this sounds like a really terrible idea, it's possible. You will need to add some more routes that will match the new actions in your controller. You won't be able to call them 'create' and 'update' because method names must be unique within the same class.

Having said that, I really beg you to rethink your approach. REST, as described in the Rails Getting Started guide, by far the standard for building Rails applications. If you're not familiar with it, I would recommend stopping where you are and reading up on it. Your application will be much easier to build and maintain, and you won't waste time asking structural questions. If you are familiar with it and are choosing to ignore it, then I wish you the best of luck.

于我来说 2024-12-28 16:26:22

你可以使用这个命令:

rails gscaffold_controller'controller_name'

或者如果是痉挛方法,你可以使用这个:

rails 生成控制器“controller_name”添加新

you can use this command:

rails g scaffold_controller 'controller_name'

or if spastic method you can use this:

rails generate controller 'controller_name' add new

凡尘雨 2024-12-28 16:26:22

假设您有一个对象 Book。您可以在 books_controller.rb 内的任何方法中更改 Book 的值,只要该方法有权访问 @book.id 即可。

def crazy_create_method
  book.create (book_params)
  book.save
end

话虽这么说,请尝试坚持使用默认的 new/create 方法,如果您稍后需要变得奇怪,那么调用属于您需要的任何方法的代码总是很容易。 Rails 将许多开箱即用的功能融入到默认的 REST 操作中。

book.title = my_title  
book.save

Let's say that you have an object Book. You can change values of Book in any method inside of your books_controller.rb as long as that method has access to @book.id.

def crazy_create_method
  book.create (book_params)
  book.save
end

That being said, try to stick to the default new/create methods and if you need to get weird later on it's always easy to call the code belong in whatever method you need. Rails bakes a lot of out of the box functionality into the default REST actions.

book.title = my_title  
book.save
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文