2011-01-09 79 views
1

我花了一些时间搞清楚这一点,并没有看到其他人张贴在上面,所以也许这将有助于某人。另外,我没有太多的Rails的经验,所以我会很感激任何更正或建议,但下面的代码似乎运作良好。使用命名范围与find_or_create_by

我已经设置了一个虚拟属性,使name在first_name和last_name之外,如Railscast on virtual attributes所述。我想通过full_name进行搜索,所以我添加了Jim's answer here中建议的named_scope。

named_scope :find_by_full_name, lambda {|full_name| 
    {:conditions => {:first => full_name.split(' ').first, 
    :last => full_name.split(' ').last}} 
} 

但是...我想能够使用所有这些:find_or_create_by_full_name。使用该名称创建命名范围仅提供搜索(它与上面的:find_by_full_name代码相同) - 即它不会按照我的要求进行操作。因此,为了处理这个我创建了一个类的方法,我称之为用户等级:find_or_create_by_full_name

# This gives us find_or_create_by functionality for the full_name virtual attribute. 
# I put this in my user.rb class. 
def self.find_or_create_by_full_name(name) 
    if found = self.find_by_full_name(name).first # Because we're using named scope we get back an array 
    return found 
    else 
    created = self.find_by_full_name(name).create 
    return created 
    end 
end 

回答

1

你可能也只是使用 User.find_or_create_by_first_name_and_last_name(:first_name => "firstname", :last_name => "last_name")