Rails active record association: has_many, has_one it returns empty array and nil respectively

Class definitions

class Bid < ActiveRecord::Base
 belongs_to :user
 has_one :project
end
class Project < ActiveRecord::Base
 belongs_to :bid
end
class User < ActiveRecord::Base
 has_many :bids
end

Corresponding migrations

create_table "users", force: true do |t|
 t.integer "sb_id"
 t.integer "bank_id"
 t.datetime "created_at"
 t.datetime "updated_at"
 t.integer "sbwb_user_id"
end
create_table "bids", force: true do |t|
  t.integer "user_id"
end
create_table "projects", force: true do |t|
  t.integer "bid_id"
end

Probems: Consider all tables are empty except ‘users’

# In rails console
pry(main)> User.first.bids

User Load (0.4ms) SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
 Bid Load (0.6ms) SELECT `bids`.* FROM `bids` WHERE `bids`.`user_id` = 1
=> []

# But If we add a record in 'Bids' table but not in 'Projects' table
pry(main)> Bid.first.project
 
Bid Load (0.7ms) SELECT `bids`.* FROM `bids` ORDER BY `bids`.`id` ASC LIMIT 1
 Project Load (0.7ms) SELECT `projects`.* FROM `projects` WHERE `projects`.`bid_id` = 1 LIMIT 1
=> nil

Conclusion

For plurals, it returns empty Array (‘[ ]‘), and for singulars such as (has_one associations) it returns nil

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s