0

I'm learning Rails and I'm trying to connect the dots between Ruby and what's going on when creating associations. For example:

class Post < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :posts
end

I've read an explanation online that relates the use of belongs_to and has_many here to attr_accessor in Ruby. This is a tad confusing ... how is that so? I understand this sets up the 1:M association between Post and User, specifically Post has a foreign key containing a user id. In the rails console, I can do something like:

user = User.first
user.posts 
user2 = User.create(username: 'some guy').save
post2 = Post.new(title: 'stuff', body: 'some more stuff')
user2.posts << post2 

So are these kind of like 'getter' and 'setter' methods where an object of each class corresponds to a specific row in the database and I can use these methods because of their association/relationship?

Ellery Temple
  • 147
  • 1
  • 5
  • have you read the Rails Guide on the subject: http://guides.rubyonrails.org/association_basics.html – Taryn East Dec 16 '14 at 05:33
  • Yes I read the rails guide. I was trying to solidify my understanding of the subject and I'm open to another explanation. – Ellery Temple Dec 16 '14 at 05:38
  • ok cool - just making sure you have a common base to start from. – Taryn East Dec 16 '14 at 05:40
  • The lines `belongs_to :user` and `has_many :posts` _automagically_ adds a load of methods to the association. So, yes, you can use them because of the association. – roob Dec 16 '14 at 05:43

1 Answers1

0

To answer your exact question, the answer is "kinda yes, kinda no".

What rails does internally to set up the association is pretty complicated. yes, getter/setter methods are involved, yes, pointing at table rows are involved... but this isn't exactly what Active Record does, and it isn't only what Active Record does.

If you really want to know what Active Record does inside: you can just go and look at the source code on github.

If you have a more specific question... I recommend you update your question to ask that :)

Taryn East
  • 27,486
  • 9
  • 86
  • 108