简体   繁体   English

Rails validates_uniqueness_of和范围-仅在更新时有效

[英]Rails validates_uniqueness_of and scope - working only on update

I have these 3 classes: 我有以下3个课程:

class Profile < ActiveRecord::Base  
end

class Subject < ActiveRecord::Base
end

class ProfileSubject < ActiveRecord::Base
  belongs_to :profile
  belongs_to :subject

  validates_uniqueness_of :subject_id, scope: :profile_id
end

And this validates_uniqueness_of works great when I update my profile with his associated collection of ProfileSubject. 当我用其关联的ProfileSubject集合更新我的个人资料时, validates_uniqueness_of效果很好。 But, on create action - it is not validated this uniqueness. 但是,在创建操作时-尚未验证此唯一性。 I thought, maybe this is because when I create object I do not have profile_id yet...and I tried add my own token for models, which I can use for connect them and validation by it (use it on scope for validates_uniqueness_of ). 我想,也许这是因为当我创建对象时,我还没有profile_id ...并且我尝试为模型添加我自己的令牌,我可以用它们来连接它们并通过它进行validates_uniqueness_of (在validates_uniqueness_of作用域上使用它)。 Ad I know now, it was not useful and not working. 我现在知道的广告,它没有用,也不起作用。

Could you help me...why this standard validation works OK on update action..but does not work on create action. 您能否帮我...为什么此标准验证对更新操作有效,但对创建操作无效。

Creation code is standard, something like this: 创建代码是标准的,如下所示:

    @profile = Profile.new(profile_params)

    if @profile.save
      # ...
    else
      # ...
    end

Use: 采用:

validates_associated :subject, :profile
validates :subject, :profile, :presence => true

In stead of: 代替:

validates_uniqueness_of :subject_id, scope: :profile_id

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

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