Rails:如何检查多态关联?

发布于 2024-10-18 05:48:30 字数 593 浏览 5 评论 0原文

我有以下模型设置:

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 和favoritable_type` 字段。

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

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

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

我正在运行 Rails 3.0.3。

I have the follow model setup:

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

And that Favorite model has favoritable_id and favoritable_type` fields.

What I ultimately want to do is check and see if a User has already marked a photo as a favorite.

I'm able to create the database record without issue...it's the checking to see if that user already has favorited the photo (or other data type) that I'm having issues with.

I could obviously do some sort of raw SQL query to get it, but seems like there's gotta be a more "standard" way of doing it.

I'm running Rails 3.0.3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你与昨日 2024-10-25 05:48:30

您可以在用户模型中添加另外两个关联以及一个检查照片是否最喜欢的方法:

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

我没有测试它,但我认为它应该有效。

you can add two other associations in the User model and a method that checks if the photo is favorite :

has_many :favorites
has_many :favorites_photos, :through => :favorites, :source => :favoritable, :source_type => 'Photo'

def photo_favorite?(photo)
  favorites_photos.exists?(photo.id)
end

or more simply just by adding this method to the Photo model :

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

I did not tested it, but I think it should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文