0
为了提高对Rails的理解,我正在转换一个使用data_mapper的Sinatra应用程序。Rails:查找数据库记录
我试图找到数据映射器'第一'方法的最佳替代品,它搜索数据库并返回所需记录的第一个实例。
任何人都可以评论,如果这样做是正确的,或者如果有更好的解决方案?
情况#1 西纳特拉
url = Url.first(:original => original)
的Rails(这些好吗?)
情况#2
西纳特拉
raise 'Someone has already taken this custom URL, sorry' unless Link.first(:identifier => custom).nil?
我的Rails(与find)
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
但这不是代码的目的。我放入OP的代码只是缩短网址的方法的一部分。我将把整个原始方法放在OP中。 – Leahcim
好的。然后我的编辑会照顾你的查询查询 –
谢谢,那么你是说我做错了吗? – Leahcim