2016-07-13 3 views
1

ActiveRecordでは、実際の属性に基づいて仮想属性を持つことがあります。 I.カスタムキーで `find_by`を拡張する

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 attribute: valueスタイルではなく、古いfind_by_*スタイルファインダーを使用している:私のような何かを行うことができます。古いスタイルを使わなくても新しいスタイルを拡張できるフックはありますか?

I.E.私がしたい:

User.find_by full_name: 'John Doe' 

むしろより:

User.find_by_full_name 'John Doe' 

答えて

0

私はそれに打撃を与える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 

を考えることができない、と思えます私の側でうまく動作します。

関連する問題