使用自定义键扩展`find_by`

时间:2016-07-13 13:51:58

标签: ruby-on-rails rails-activerecord

在ActiveRecord中,有时您会有基于真实属性的虚拟属性。即。

class User < ApplicationRecord
  def full_name
    [first_name, last_name].reject(&:blank?).join ' '
  end

  def full_name= new_val
    self.last_name, self.first_name = *new_val.reverse.split(' ', 2).each(&:reverse!)
  end
end

现在我想说我想支持全名搜索。我可以这样做:

class User < ApplicationRecord
  def self.find_by_full_name name
    where("first_name || ' ' || last_name = ?", name).first
  end
end

这样可行,但搜索方法使用较旧的find_by_*样式查找器而不是较新的find_by attribute: value样式。是否有一个钩子,我可以扩展更新的风格,而不是必须使用旧风格?

即。我想要:

User.find_by full_name: 'John Doe'

而不是:

User.find_by_full_name 'John Doe'

1 个答案:

答案 0 :(得分:1)

除了覆盖User模型中的find_by方法之外,我无法想到任何其他内容

class User < ApplicationRecord
   def self.find_by(*args)
     if args.first.key?(:full_name)
       where("first_name || ' ' || last_name = ?", args.first[:full_name]).where(args.first.except(:full_name)).take
     else
       super(*args)
     end
   end
 end

试一试,似乎在我身边工作正常。