【问题标题】:Rails validates_uniqueness_of and scope - working only on updateRails validates_uniqueness_of 和范围 - 仅在更新时工作
【发布时间】:2015-08-30 10:04:56
【问题描述】:

我有这 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

当我用他关联的 ProfileSubject 集合更新我的个人资料时,这个 validates_uniqueness_of 效果很好。但是,在创建操作时 - 它没有验证这种独特性。我想,这可能是因为当我创建对象时我还没有 profile_id ......我尝试为模型添加我自己的令牌,我可以使用它来连接它们并通过它进行验证(在validates_uniqueness_of 的范围内使用它)。我现在知道的广告,它没有用,也不起作用。

你能帮我吗...为什么这个标准验证在更新操作上可以正常工作..但在创建操作上不起作用。

创建代码是标准的,像这样:

    @profile = Profile.new(profile_params)

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

【问题讨论】:

  • 你能告诉我们创建代码吗?

标签: ruby-on-rails validation validates-uniqueness-of


【解决方案1】:

用途:

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

代替:

validates_uniqueness_of :subject_id, scope: :profile_id

【讨论】:

  • 我不需要只存在主题和个人资料。我需要个人资料范围内主题的唯一性。在我的应用程序中意味着 Profile 可以有许多 ProfileSubject 并且在此配置文件的范围内,这些 ProfileSubjects 需要具有唯一性主题
猜你喜欢
  • 2017-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多