88

Imagine the following situation:

I have a dog model and a house model. A dog can belong to a house, and a house can have many dogs, so:

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 don't have a house. They don't belong to house. Can I still use that relationship structure and simply don't inform a :house_id when creating it?

Is there a better practice?

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

2
  • 2
    yes..you can leave house_id null and when you @dog.house it will return nil and so you can check it like if @dog.house and so on..
    – rubyprince
    May 5, 2012 at 14:39
  • 2
    To make sure this works, in your database, the Dog table should not have the null part of t.integer "house_id", :null => false.
    – Ashitaka
    May 5, 2012 at 14:41

2 Answers 2

366

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, it will trigger a validation error when trying to save a model where belongs_to associations are not present.

config.active_record.belongs_to_required_by_default can be changed to false and with this keep old Rails behavior or we can disable this validation on each belongs_to definition, just passing an additional option optional: true as follows:

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

from: https://sipsandbits.com/2015/09/21/whats-new-in-rails-5/#belongs_toisrequiredbydefault

2
  • 32
    this is the answer to Rails 5 users Jun 22, 2016 at 15:25
  • 3
    Spent 2 nights on this one... thanks guys. Can confirm optional: true does the trick. My use case was: class User < ApplicationRecord belongs_to :team, optional: true end class Team < ApplicationRecord has_many :users end Aug 28, 2016 at 3:28
28

I think it is absolutely normal approach.

You can just leave house_id with null value in database for the models which don't belong to other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.