Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord验证:关联上的唯一性_Ruby On Rails_Ruby_Validation_Activerecord - Fatal编程技术网

Ruby on rails ActiveRecord验证:关联上的唯一性

Ruby on rails ActiveRecord验证:关联上的唯一性,ruby-on-rails,ruby,validation,activerecord,Ruby On Rails,Ruby,Validation,Activerecord,我需要执行验证,以确保给定类别中只能存在一个公司内的用户 validates :user_id, :uniqueness => {:scope => [:category, :company_id], :message => "already exists"} 除了在:user\u id键上设置了错误消息外,此操作有效 我如何才能在:user键上设置错误(validates:user给出错误)?我认为这是不可能的,因为ActiveRecord的validates方法会将

我需要执行验证,以确保给定类别中只能存在一个公司内的用户

  validates  :user_id, :uniqueness => {:scope => [:category, :company_id], :message => "already exists"}
除了在
:user\u id
键上设置了错误消息外,此操作有效


我如何才能在
:user
键上设置错误(
validates:user
给出错误)?

我认为这是不可能的,因为ActiveRecord的validates方法会将错误发送到正在验证的方法

因此验证:user尝试发送到:user的attr_访问器,该访问器在您的模型中不存在

不过,如果您只是想让错误消息变得漂亮,您可以:

alias user user_id
然后在验证中使用:user

validates  :user, :uniqueness => {:scope => [:category, :company_id], :message => "already exists"}
另一方面,我不会在别名中使用user,而是类似于:

alias the_supplied_user user_id
然后在验证中:

validates  :the_supplied_user, :uniqueness => {:scope => [:category, :company_id], :message => "already exists"}

下面是一种检查唯一性并强制将错误分配给
:user
属性的简单方法:

class User < ActiveRecord::Base
  validate :user_unique_per_company_per_category

  private

  def user_unique_per_company_per_category
    if self.class.exists?(:user_id => user_id, :company_id => company_id, :category => category)
      errors.add :user, 'already exists'
    end
  end
end

验证:user,:university=>{…}
?可能重复-@Martin我在问题中提到过,它会引发错误。建议的副本是一个完全不同的问题。对不起,这个问题确实完全不同,我应该在回答这个问题时提到一个可能的解决方案。我想它很快就会被修复:)好吧,用户和用户id都存在,因为它是一个关联。所以别名会破坏一切。是的,到目前为止,自定义验证可能是最好的选择。我不敢相信您不能对用户应用此验证:(验证用户id的问题是,它从未在UI上使用过,因此您提到的错误消息将不在正确的位置。当您编辑
用户
记录时,这是否也起作用?您要保存的用户可能已经在数据库中,但如果您正在更新,则可以。
errors.add :base, 'already exists'