Rails评论关联模型结构

时间:2015-06-23 19:25:38

标签: ruby-on-rails ruby

我正在建立一个小型的博客网站,其中一些模型显然是帖子,用户,评论。

问题是:评论模型/表的结构是否正确?我之所以这样问是因为它看起来像有许多关联,但我只使用有很多。 我有点困惑。

这种结构是否正确?

我可能需要稍后将评论关联添加到其他模型。

PS。现在,下面的代码对我来说很好。

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

1 个答案:

答案 0 :(得分:3)

是的,关系定义正确。

当关系通过另一个模型时,使用

has_many though

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

此处的关键是songs表没有artist_id列,而是在查询song.bandband.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>