glesage
glesage

Reputation: 975

Rails belongs_to vs parent_id

Generic active record questions:
- Advantages/disadvantages of belongs_to association vs a parent_id column?
- Conventions regarding the 2?
- Does belongs_to association enforce :null => false ?

class CreateIssues < ActiveRecord::Migration

def change
  create_table :issues do |t|
    t.belongs_to :project

    t.timestamps
  end
end

VS

class CreateIssues < ActiveRecord::Migration

def change
  create_table :issues do |t|
    t.integer :project_id, :null => false

    t.timestamps
  end
end

Thanks alot!

Upvotes: 0

Views: 76

Answers (1)

jbeck
jbeck

Reputation: 2254

belongs_to() is just an alias to references(), which does not enforce the (:null => false) condition. Check out the source.

I find it's more common to use references(), but again, belongs_to() is a valid alias.

It's uncommon to see the reference written out manually, as its part of the way ActiveRecord simplifies these associations.

Upvotes: 1

Related Questions