Skip to content

Instantly share code, notes, and snippets.

@JustSilverman
Last active December 10, 2015 23:19
Show Gist options
  • Save JustSilverman/4508809 to your computer and use it in GitHub Desktop.
Save JustSilverman/4508809 to your computer and use it in GitHub Desktop.
Association using :inverse_of option.
class Company < ActiveRecord::Base
has_many :users, :inverse_of => :company
end
class User < ActiveRecord::Base
belongs_to :company, :inverse_of => :users
end
# Code from the Consle
# irb(main):001:0> u = User.last
# User Load (0.9ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
# => #<User id: 123, first_name: "Melissa", created_at: "2013-01-11 06:37:19", updated_at: "2013-01-11 06:37:19", password_digest: "$2a$10$iAa.v2FPD7DqnwZEvQrr2.RNwVG/wSJBTfO66YfosDou...", remember_token: "QbE7RM4xeBmeky2kVv7KxQ", admin: nil, last_name: "Post", title: "Co-Founder", frequency: 1, address_id: 141, company_id: 62, password_reset_sent_at: nil, password_reset_token: nil, linkedin_profile: "www.linkedin.com/", invitation_id: nil, invitation_limit: 5, birthdate: "1981-04-06", own_industry_id: 377, objective: ["1", "7"], day_preference: 4, time_zone: "Eastern Time (US & Canada)", avatar_file_name: nil, avatar_content_type: nil, avatar_file_size: nil, avatar_updated_at: nil, status: 2>
# irb(main):002:0> c = Company.find(62)
# Company Load (7.7ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1 [["id", 62]]
# => #<Company id: 62, name: "Vandelay Industries", created_at: "2013-01-11 05:07:45", updated_at: "2013-01-11 05:07:45">
# irb(main):003:0> c.users.count
# (0.5ms) SELECT COUNT(*) FROM "users" WHERE "users"."company_id" = 62
# => 1
# irb(main):004:0> u.first_name == c.users.first.first_name
# User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."company_id" = 62 LIMIT 1
# => true
# irb(main):005:0> u.first_name = "New Name"
# => "New Name"
# irb(main):006:0> u.first_name == c.users.first.first_name
# User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."company_id" = 62 LIMIT 1
# => false
# I think I understand why this returns false (it's retrieving a new instance of c's first user from the db,
# which has yet to be updated), but based on the following documentationf from the Rails Guide below, I
# would have expected it to reference the instance with the updated name
# From the guide http://guides.rubyonrails.org/association_basics.html
class Customer < ActiveRecord::Base
has_many :orders, :inverse_of => :customer
end
class Order < ActiveRecord::Base
belongs_to :customer, :inverse_of => :orders
end
c = Customer.first
o = c.orders.first
c.first_name == o.customer.first_name # => true
c.first_name = 'Manny'
c.first_name == o.customer.first_name # => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment