Best practices regarding empty association_to association

Imagine the following situation:

I have a dog model and a house model. A dog can belong to a house, and there can be many dogs in a house, therefore:

 Class Dog < ActiveRecord::Base belongs_to :house end Class House < ActiveRecord::Base has_many :dogs end 

Now imagine that I also want to create dogs that do not have a home. They do not belong to the house. Can I use this relationship structure and just not tell :house_id when I create it?

Is there a better practice?

Arr .: I used this analogy to simplify my problem, but my real situation is this: I have a model that the user can generate instances of. He can also create collections of these instances, but he can leave the instance outside the collection.

+42
ruby ruby-on-rails activerecord
May 05 '12 at 2:14 pm
source share
2 answers

I think this is an absolutely normal approach.

You can simply leave house_id with a null value in the database for models that do not belong to others.

+20
May 5 '12 at 2:36 pm
source share

Be careful with this in Rails 5 ...

belongs_to is required by default

From now on, every Rails application will have a new configuration option config.active_record.belongs_to_required_by_default = true, this will lead to a validation error when trying to save a model where there belongs_to no associations.

config.active_record.belongs_to_required_by_default can be changed to false, and the behavior of old Rails is preserved, or we can disable this validation for each belongs_to property, simply passing an additional option optional: true as follows:

 class Book < ActiveRecord::Base belongs_to :author, optional: true end 

from: http://blog.michelada.io/whats-new-in-rails-5

+180
Mar 03 '16 at 15:02
source share



All Articles