Validating presence of parent in a nested model

Let’s figure a simple scenario where a client has multiple notes. We want to be able to define notes as we create the client, such as:

where notes_param would be:

And we expect notes to be generated for that client. That’s pretty basic stuff. What is more tricky is how to validate that the client exists when building the notes. Your models should look somewhat like (trimmed down to the basic stuff):

Doing so would result in an error that would basically says that “Client cannot be empty.”. This is because the notes have no idea that the client was defined because it’s the parent object. To make it work, you would have to review the Client model and add a simple parameters to the notes associations:

With this little addition, the notes will know for which client they are being generated.

Question is: Why isn’t this guessed by Rails? Why do we have to add it manually? Well, you can make this automatically loaded for every relation. Just add the following line into config/application.rb:

USE WITH CARE. This is disabled by default for performance issues. I do not recommend making this the default in a production application.

Structure of a model

When it comes down to coding conventions, I’m always eager to learn. Best practices, coding standards, naming conventions are meant to produce clean, readable code. When coding my Ruby On Rails models, I usually go with the following structure:

There are quite a few interesting things in that simple model. First of all, I use the Annotate gem to get my model fields listed in a comment at the start of the file. This is pretty handy for a lot of things, including auto-completion from my editor.

These days, I mostly use Ruby on Rails as an API for my frontend. That introduces two concepts for my models: can_delete?  and as_json .

First off, as_json  returns a simplified version of my model, excluding fields that are not required by the front end.

Second, can_delete?  ensure that the model can be deleted, whether a DELETE  call was issued to the right controller. This is a security net that forces me to think about the conditions where this model can be deleted. Sometimes it’s a simple static true  that is returned, sometimes this is a more complex set of rules. At least I know I have given a thought about whether this model can be deleted or not.

Lastly, the parameters for as_json  is named _options , starting with an underscore. When a parameter is not going to be used, I prefix it with an underscore so I know this is not used.

So that’s it, this is my basic file structure. I will cover more advanced topics in a future post.