Rails:如何检查多态关联?
我有以下模型设置:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在用户模型中添加另外两个关联以及一个检查照片是否最喜欢的方法:
或者更简单地只需将此方法添加到照片模型中:
我没有测试它,但我认为它应该有效。
you can add two other associations in the User model and a method that checks if the photo is favorite :
or more simply just by adding this method to the Photo model :
I did not tested it, but I think it should work.