Inverse_of ActiveRecord::Base

While reading the documentation of ActiveRecord::Associations, there are many useful methods, that I didn´t know about it. But one came to me as quite useful, inverse_of. This method allow us to work with associations that haven`t been save yet, so it will work with the memory. This will optimise our object loading.

I will so you with some example.

1
2
3
4
5
6
7
Class Post < ActiveRecord::Base
  has_many :comments, inverse_of :post
end

Class Comment < ActiveRecord::Base
  belongs_to :post, inverse_of :comments
end

Setting like this our models will allow to do some nice thing in our console.

1
2
3
4
5
6
p = Post.create
=> #<Post id: nil, name: nil >
c = p.comments.create
=> #<Comment id: nil, body: nil >
c.post
=> #<Post id: nil, name: nil >

Without the inverse the last line will return nil because is trying to hit the database but there isn’t any record save in it

Comments