Rails comment associations association structure

I am creating a small blog and some of its models are post, user, comment, obviously.

Question: Is the model / comment table correct? I ask this because it looks like it has many links , but I only use those that have many . I am a bit confused.

Is this structure correct?

I may have to add the association of comments to other models later.

ps. Right now, the code below is working fine for me.

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :body
      t.references :user, index: true, foreign_key: true
      t.references :post, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

      

-

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments, dependent: :destroy
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments, dependent: :destroy
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

      

+3


source to share


1 answer


Yes, the attitude is defined correctly.

has_many though

used when the relationship goes through another model:

class Band
  has_many :albums
  has_many :songs, through: :albums
end

class Album
  belongs_to: :band
  has_many :songs
end

class Song
  belongs_to :album
  has_one :band, though: :album
end

      



The key here is the table songs

does not have a column artist_id

and you need to join the album table when querying for song.band

or band.song

.

irb(main):009:0> Song.find_by(name: 'Sympathy for the Devil').band
  Song Load (0.3ms)  SELECT  "songs".* FROM "songs" WHERE "songs"."name" = ? LIMIT 1  [["name", "Sympathy for the Devil"]]
  Band Load (0.1ms)  SELECT  "bands".* FROM "bands" INNER JOIN "albums" ON "bands"."id" = "albums"."band_id" WHERE "albums"."id" = ? LIMIT 1  [["id", 4]]
=> #<Band id: 4, name: "Rolling Stones", created_at: "2015-06-23 20:08:14", updated_at: "2015-06-23 20:08:14">
irb(main):010:0> 

      

+3


source







All Articles