Beginner's guide for activerecord relationships
class Book
belongs_to :author
end
class Supplier
has_one :account
end
class Author
has_many :books
end
class Doctor
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment
belongs_to :patient
belongs_to :doctor
end
class Patient
has_many :appointments
has_many :doctors, through: :appointments
end
class Supplier < ApplicationRecord
has_one :account
has_one :account_history, through: :account
end
class Account < ApplicationRecord
belongs_to :supplier
has_one :account_history
end
class AccountHistory < ApplicationRecord
belongs_to :account
end
class Assembly < ApplicationRecord
has_and_belongs_to_many :parts
end
class Part < ApplicationRecord
has_and_belongs_to_many :assemblies
end
belongs_to
(this model will have the foreign key) and
the other model a has_one
has_and_belongs_to_many
.through:
clause.class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
@employee.pictures
or @product.pictures
.@picture.imageable
. To do so, you must declare 2 feilds in the polymorphic model:
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
add_index :pictures, [:imageable_type, :imageable_id]
end
end
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
modelname_count
column to the belonging model's migration:# Posts table
add_column :posts, :comments_count, :integer, default: 0
#add_column belonging_to table name, :which table to count _count, :integer, default: 0
class Comment < ActiveRecord::Base
belongs_to :post, :counter_cache => true
end
Post.find_each { |post| Post.reset_counters(post.id, :comments) }
class AddCommentsCountToPosts < ActiveRecord::Migration
def change
change_table :posts do |t|
t.integer :comments_count, default: 0
end
reversible do |dir|
dir.up { data }
end
end
def data
execute <<-SQL.squish
UPDATE posts
SET comments_count = (SELECT count(1)
FROM comments
WHERE comments.post_id = posts.id)
SQL
end
end