【发布时间】: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