【问题标题】:Rails: How do I check a polymorphic association?Rails:如何检查多态关联?
【发布时间】:2011-02-16 16:26:58
【问题描述】:

我有以下模型设置:

class Favorite < ActiveRecord::Base
  belongs_to :favoritable, :polymorphic => true
  belongs_to :user
end

class Photo < ActiveRecord::Base
  belongs_to :user
  has_many :favorites, :as => :favoritable
end

class User < ActiveRecord::Base
  has_many :photos
end

Favorite 模型有 favoritable_id 和 favouritable_type` 字段。

我最终想要做的是检查User 是否已将照片标记为收藏。

我能够毫无问题地创建数据库记录...这是检查该用户是否已经收藏了我遇到问题的照片(或其他数据类型)。

我显然可以执行某种原始 SQL 查询来获取它,但似乎必须有一种更“标准”的方式来做到这一点。

我正在运行 Rails 3.0.3。

【问题讨论】:

    标签: ruby-on-rails associations polymorphic-associations


    【解决方案1】:

    您可以在 User 模型中添加另外两个关联和一个检查照片是否为收藏的方法:

    has_many :favorites
    has_many :favorites_photos, :through => :favorites, :source => :favoritable, :source_type => 'Photo'
    
    def photo_favorite?(photo)
      favorites_photos.exists?(photo.id)
    end
    

    或者更简单,只需将此方法添加到照片模型:

    def favorite_for?(user)
      favorites.exists?(:user_id => user.id)
    end
    

    我没有测试它,但我认为它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      相关资源
      最近更新 更多