简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM