flyingarmadillo
flyingarmadillo

Reputation: 2139

Create a new action for existing controller

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?

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

rails g controller products [new_action]

and then rails would insert:

def [new_action]

end

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.

Upvotes: 12

Views: 12161

Answers (3)

Carlos Matte
Carlos Matte

Reputation: 11

we can create manually the action in the controller and view but you should also add test statements that because should be good automated process, something like rails generate controller NAME [action action] option m m = merge

Upvotes: 1

Outside_Box
Outside_Box

Reputation: 465

Rails provide posibility of creating custom generators (but this is more advanced subject), which can be tailored for your needs.

More info:

http://guides.rubyonrails.org/generators.html

Upvotes: 0

Peter Brown
Peter Brown

Reputation: 51697

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.

Upvotes: 17

Related Questions