1

我花了一些时间弄清楚这一点,还没有看到其他人在上面发帖,所以也许这会对某人有所帮助。另外,我没有太多的 Rails 经验,所以我会很感激任何更正或建议,尽管下面的代码似乎运行良好。

正如Railscast on virtual attributes中所讨论的那样,我已经设置了一个虚拟属性来使用 first_name 和 last_name 生成 full_name 。我也想按 full_name 搜索,所以我添加了一个 named_scope,正如Jim 的回答中所建议的那样。

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
4

1 回答 1

1

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

于 2011-01-10T10:54:59.403 回答