通过多态类的关系从has_many获取所有相关实例

时间:2016-03-16 18:29:06

标签: ruby-on-rails activerecord polymorphism has-many-through

我试图让用户为我的项目中的内容创建方式。为此,我建立了如下的多态关系

喜欢表

table "likes", force: :cascade do |t|
  t.integer  "likeable_id"
  t.string   "likeable_type"
  t.integer  "user_id",       null: false
  t.datetime "created_at"
  t.datetime "updated_at"
end

模型

class User < ActiveRecord::Base
  has_many :likes, dependent: :destroy
  has_many :newsletters, through: :likes, source: :likeable, source_type: "newsletter"
  has_many :gift_cards, through: :likes, source: :likeable, source_type: "gift_card"
  has_many :stories, through: :likes, source: :likeable, source_type: "story"
end

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :likeable, polymorphic: true
end

class Newsletter < ActiveRecord::Base
  has_one :like, as: :likeable, dependent: :destroy
  has_one :user, through: :like, source: :likeable
end

class GiftCard < ActiveRecord::Base
  has_many :likes, as: :likeable, dependent: :destroy
  has_many :users, through: :likes, source: :likeable
end

class Story < ActiveRecord::Base
  has_many :likes, as: :likeable, dependent: :destroy
  has_many :users, through: :likes, source: :likeable
end

tldr:用户通过这些喜欢有很多喜欢和许多简报,礼品卡和故事。

我的问题,有了这种结构,最好的方法是获得用户喜欢的一切吗?

2 个答案:

答案 0 :(得分:1)

对我来说,这对于一个域来说非常难以理解,实际上是非常简单的。也许你有更大的理由以这种方式实现它,但这是我对User LikeGiftCard模型的建议(这可能会有所帮助!)。

class User < ActiveRecord::Base
  has_many :likes, dependent: :destroy
  has_many :liked_giftcards, through: :likes, source: :giftcard
end

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :giftcard
end

class GiftCard < ActiveRecord::Base
  has_many :likes, dependent: :destroy
end

class Story < ActiveRecord::Base
  ...same as GiftCard
end

就我个人而言,我觉得这更容易理解。它可以通过user.likes轻松访问用户喜欢的所有内容,并允许您通过user.liked_giftcards等单独查看每个类别。

答案 1 :(得分:0)

结束搞清楚。只是有一些小的语法错误

class User < ActiveRecord::Base
  has_many :likes, dependent: :destroy
  has_many :newsletters, through: :likes, source: :likeable, source_type: "Newsletter"
  has_many :gift_cards, through: :likes, source: :likeable, source_type: "GiftCard"
  has_many :stories, through: :likes, source: :likeable, source_type: "Story"
end

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :likeable, polymorphic: true
end

class Newsletter < ActiveRecord::Base
  has_one :like, as: :likeable, dependent: :destroy
  has_one :user, through: :like
end

class GiftCard < ActiveRecord::Base
  has_many :likes, as: :likeable, dependent: :destroy
  has_many :users, through: :likes
end

class Story < ActiveRecord::Base
  has_many :likes, as: :likeable, dependent: :destroy
  has_many :users, through: :likes
end