简体   繁体   English

验证多态关联中一个或多个模型实例的限制

[英]Validating limit of one or more instances of a model in a polymorphic association

I have a model Photos with polymorphic associations that is supposed to hold the photos used by other models let say Post and Profile. 我有一个具有多态关联的模型照片 ,该模型应该保存其他模型使用的照片,比如说Post和Profile。

I'm trying to validate that: 我正在尝试验证这一点:

  1. Each instance of Post could only be associated to only one instance of Photo 每个Post实例只能与一个Photo实例关联
  2. Each instance of Profile could be associated to one or more instances of Photo. 每个配置文件实例可以与一个或多个照片实例相关联。

I'm trying to use the following validation code in my Photo model without success 我试图在我的照片模型中使用以下验证代码失败

 class Photo < ApplicationRecord
  belongs_to :photoable, polymorphic: true
  validates_uniqueness_of :photoable_id, scope: :photoable_type
end

I was assuming the scope in this validation would instruct Rails to reject repeating ids only for each :photoable_type but what really happens is that Rails rejects any repeating id regardless if the type is set to 'Profile' or 'Post' (eg I can only have one instance of Photo with photoable_id == 1 whilst I wish I could have two instances with same photoable_id as long as one has photoable_type == 'Profile' and the other a photoable_type == 'Post') 我假设此验证的范围将指示Rails仅拒绝每个:photoable_type的重复ID,但实际上发生的是Rails拒绝任何重复的ID,无论类型是否设置为'Profile'或'Post'(例如,我只能有一个photoable_id == 1的Photo实例,而我希望我可以有两个具有相同photoable_id的实例,只要一个实例具有photoable_type =='Profile',另一个具有photoable_type =='Post')

Could you help explaining how to achieve this and why scope won't work like that? 您能否帮助解释如何实现这一目标,以及为什么示波器不能那样工作? It would have been the same outcome to have left 'scope: :photoable_type' out of the validation code. 将'scope::photoable_type'排除在验证代码之外也是一样的结果。

The code in the other 2 models below: 下面的其他2个模型中的代码:

Post model 发布模型

class Post < ApplicationRecord
  has_one :photo, as: :photoable
end

Profile model 轮廓模型

class Profile < ApplicationRecord
  has_many :photos, as: :photoable
end

I used the code suggested in the following post to solve the issue. 我使用以下帖子中建议的代码来解决此问题。 Validate scoped uniqueness in polymorphic association models. 验证多态关联模型中的范围唯一性。

In this case a working solution would be: 在这种情况下,可行的解决方案是:

  validates_uniqueness_of : photoable_id, scope: [: photoable_type, :photoable_id]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM