【问题标题】:Using named scope with find_or_create_by将命名范围与 find_or_create_by 一起使用
【发布时间】:2011-06-06 06:32:28
【问题描述】:

我花了一些时间来解决这个问题,还没有看到其他人在上面发帖,所以也许这会对某人有所帮助。另外,我没有太多 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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      相关资源
      最近更新 更多