validates_uniqueness_of elasticsearch持久性

时间:2016-03-08 04:17:39

标签: ruby validation ruby-on-rails-4 elasticsearch elasticsearch-ruby

如何validates_uniqueness_of弹性搜索持久性。我有一个带有include语句的模型

include Elasticsearch::Persistence::Model

我想要包含一个唯一性验证 validates_uniqueness_of :username

当我尝试使用new函数进行初始化时 NoMethodError: undefined method validates_uniqueness_of for class

微量

undefined method `validates_uniqueness_of' for #<Profile:0x007fd83c2b8a10>
    from profile.rb:22:in `block in <class:Profile>'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:446:in `instance_exec'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:446:in `block in make_lambda'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:164:in `call'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:164:in `block in halting'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:504:in `call'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:504:in `block in call'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:504:in `each'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:504:in `call'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:92:in `__run_callbacks__'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:778:in `_run_save_callbacks'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.4/lib/active_support/callbacks.rb:81:in `run_callbacks'
    from /Users/a6001096/.rvm/gems/ruby-2.2.2/gems/elasticsearch-persistence-0.1.8/lib/elasticsearch/persistence/model/store.rb:51:in `save'
    from (irb):5



class Profile
  include Elasticsearch::Persistence::Model

  attribute :user_id
  attribute :username, String, mapping: { index: 'not_analyzed' }
  attribute :image_url

  validates_uniqueness_of :username

end

2 个答案:

答案 0 :(得分:0)

validates_uniqueness_ofclass method of ActiveRecord

您的Profile课程应使用elasticsearch-model来定义,而不是

require 'elasticsearch/model'

class Profile < ActiveRecord::Base
  include Elasticsearch::Model

  attribute :user_id
  attribute :username, String, mapping: { index: 'not_analyzed' }
  attribute :image_url

  validates_uniqueness_of :username
end

答案 1 :(得分:0)

不改变Elasticsearch::Persistence::Model我基本上必须创建自己的验证,因为除了presence之外我没有看到任何验证。简而言之,您必须设置must search以确保它不存在

profiles = Profile.search query:{bool:{must:[{match:{username: "xxxxx"}}]}}