将命名范围与find_or_create_by一起使用

时间:2011-01-09 23:56:15

标签: ruby-on-rails named-scope virtual-attribute

我花了一些时间来搞清楚这一点,并没有看到其他人发布它,所以这可能会帮助某人。此外,我没有太多的Rails经验,所以我会感激任何更正或建议,虽然下面的代码似乎运作良好。

我已经设置了一个虚拟属性,以便在Railscast on virtual attributes 中讨论的first_name和last_name之外生成full_name。我也希望按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代码相同) - 即它不能完成我想要的操作。所以为了处理这个问题,我为我的User类创建了一个类方法: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 个答案:

答案 0 :(得分:1)

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