为现有控制器创建一个新动作 [英] Create a new action for existing controller

查看:23
本文介绍了为现有控制器创建一个新动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能是一个新手问题,但是否可以从现有控制器上的命令行创建新操作(控制器和关联视图中的方法)?

I know this is probably a newbie question, but is it possible to create a new action (method in controller & associated view) from the command line on an existing controller?

例如,我已经有一个名为Products"的控制器.我能跑吗:

For example, I already have a controller named 'Products'. Could I run:

rails g controller products [new_action]

然后 rails 会插入:

and then rails would insert:

def [new_action]

end

进入我的产品控制器并在 views/products/目录中创建一个名为[new_action].html.erb"的新文件?我已经用谷歌搜索了这个,但没有返回满意的答案.此外,我会继续尝试,但我对当前应用程序的开发非常深入,真的不想搞砸任何事情.

Into my products controller and create a new file called '[new_action].html.erb' in the views/products/ directory? I have already googled this, but no satisfactory answer was returned. Also, I would just go ahead and try it, but I am pretty far into the development of my current app and really do not want to mess anything up.

推荐答案

我很确定您无法以 100% 的自动化方式执行此操作.原因是 Rails 不知道您对路由或控制器做了什么,并且需要一些逻辑才能知道如何更新这些现有文件.最好的办法是手动添加新操作.将新方法添加到您的控制器,更新您的路由文件,并添加视图.最多可能需要 1 分钟.此外,如果您没有使用版本控制器(您的问题未涉及),那么您不必担心它会自动覆盖某些内容.

I'm pretty sure you won't be able to do this in a 100% automated way. The reason is that Rails doesn't know what you've done with your routes or controller, and it would require some logic to know how to update these existing files. Your best bet is to just add the new action manually. Add the new method to your controller, update your routes file, and add the view. It will probably take 1 minute at most. Also, if you're not using version controller (which your question eluded to), then you don't have to worry about it automatically overwriting something.

这篇关于为现有控制器创建一个新动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆