I think I can give you a quick rundown.
You're used to dealing with SQL directly, and the nice thing is that Rails promotes good database design. If you have a books table and a chapters table, then a book will have many chapters, correct? So just as in other database setups, the chapter table should have a foreign key telling what book it belongs to.
Assuming you have this foreign key in the chapters table, you can setup your Book model like so:
# app/models/book.rb
class Book < ActiveRecord::Base
has_many :chapters
end
You're telling Rails that a book literally has many chapters. So if you have a book object, you can say book.chapters
and that will return an array of the chapter objects that belong to this book. Rails will know to look at the chapters table for the book_id
foreign key, no custom SQL required.
Conversely, assuming this same database setup, you can define your chapter model to be associated with books, like this:
# app/models/chapter.rb
class Chapter < ActiveRecord::Base
belongs_to :book
end
Notice :book
here is singular, just an idiom that helps readability, since a chapter can only belong to a single book. Now if you have a chapter object and say chapter.book
, it will return the book object that the chapter belongs to.
Just as in other database applications, the foreign key is always on the "belonged to" table.
I hope this helps!