Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails .create() versus controller#create

This is a Rails newbie question:

When I call create() on a model, does it bypass the associated controller create action?

For example, this isn't hitting my tags controller #create action:

user.tags.create(:content => new_tag)

But if I POST to the tags#create route from a form then it works just fine.

I assumed that calling user.tags.create would call the controller action and always run the code in it upon create, but apparently it's only during a POST to that route.

What am I missing here?

Edit:

Is there a way to make that call then to ensure the controller create code is run? I have some code to find a tag by permalink and create a new one if necessary, else re-use an existing one. Using model.create() isn't running any of that code. I could be "doing it wrong" though :P

like image 327
iwasrobbed Avatar asked Dec 08 '25 10:12

iwasrobbed


1 Answers

The model knows nothing about the controller, it is simply an object representing state stored in the database, possibly with some additional encapsulated behaviors. The controller is an object that responds to requests made to your server. While the default scaffolding will modify your model, controllers do not have to even use a model.

Controllers and Models are disconnected, but only logically related classes.

If you have code that you want available to all users of your model, then add a method to your model. Then invoke that method from your controller, and anywhere else you'd like that behavior.

like image 148
Paul Alexander Avatar answered Dec 10 '25 01:12

Paul Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!