1:n has_many Association

Let’s explain 1:n relationships in Rails

Topics

Example

rails generate model book title
rails generate model author book_id:integer first_name last_name
rake db:migrate

Database

There are actual database
Book

id:integer
title:string
created_at:datetime
update_at:datetime

Author

id:integer
book_id:integer
first_name:string
last_name:string
created_at:datetime
updated_at:datetime

Add relationships

has_many, belongs_to are for it!
Name expresses use case.
model/book.rb

class Book < ActiveRecord::Base
  has_many:authors
end
&#91;/ruby&#93;
model/author.rb
&#91;ruby&#93;
class Author < ActiveRecord::Base
  belongs_to:book
end
&#91;/ruby&#93;

<h3><a name="addnewdata">Add new data</a></h3>
[ruby]
book = Book.create(title:'We are')
book = Author.create(book_id:book.id, first_name:'Thunder', last_name'Toon')

Practical way

book = Book.create(title:'We are')
author = book.authors.create(first_name:'Thunder', last_name'Toon')

build

build resembles create but not saved

book = Book.create(title:'Good!')
author = book.authors.build(first_name:'' last_name:'')
author.new_record?
author.save

Accessing records

Book.first
Book.first.authors
Author.first.book

join

Search book by author name.
It resembles SQL join

Book.joins(:authors).where(:authors => {last_name:'MAX'})

Reverse, search author by book name.

Author.joins(:book).where(:books => {title:'BOOK'})

includes

includes is very similar to the method joins

Book.includes(:authors).where(:authors => {last_name:'MAX'})

Delete, Destroy

destroy, destroy_all, delete, delete_all

book.authors.count
book.authors.destroy_all
book.authors.count

The difference is the way to handle relationship instance.

Options of belongs_to

touch:true

When update_at of Parent is edited, child is updated too.


class Author < ActiveRecord::Base belongs_to :book,touch:true end [/ruby]

Options of has_many

order: :last_name

Sort by subname


class Author < ActiveRecord::Base belongs_to :book,touch:true end [/ruby]

dependent: :destroy

It’s kind of CASCADE


class Book < ActiveRecord::Base has_many :authors, dependent: :destroy end [/ruby]