为了提高我对 Rails 的理解,我正在转换一个使用 data_mapper 的 Sinatra 应用程序。
我正在尝试为搜索数据库并返回所寻求记录的第一个实例的数据映射器“第一”方法找到最佳替代品。
任何人都可以评论这样做是否正确,或者是否有更好的解决方案?
情况 #1 西纳特拉
url = Url.first(:original => original)
Rails(这两个都好吗?)
url = Url.find_by_original(original) #this find_by_original
url = Url.where(:first_name => 'original')
情况#2
辛纳特拉
raise 'Someone has already taken this custom URL, sorry' unless Link.first(:identifier => custom).nil?
我的 Rails(带查找)
raise 'Someone has already taken this custom URL, sorry' unless Link.find(:identifier => custom).nil? #this Link.find
原始上下文是一种缩短 url 的方法
def self.shorten(original, custom=nil)
url = Url.first(:original => original)
return url.link if url
link = nil
if custom
raise 'Someone has already taken this custom URL, sorry' unless Link.first(:identifier => custom).nil?
raise 'This custom URL is not allowed because of profanity' if DIRTY_WORDS.include? custom
transaction do |txn|
link = Link.new(:identifier => custom)
link.url = Url.create(:original => original)
link.save
end
else
transaction do |txn|
link = create_link(original)
end
end
return link
end