2012-09-09 46 views
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 

回答

0

你可以只使用验证模型上的方法。只需在Url模型(app/models/url.rb)中执行validates_uniqueness_of :first_name即可。也有在Rails guides

编辑

其他可用的验证如果你真的想找到,如果这样的记录手动存在。你可以做Url.find(:first, :conditions => { :first_name => 'original' })和检查零

raise 'Someone has already taken this custom URL, sorry' unless Link.find(:first, :conditions => { :identifier => custom }).nil? 

另外,如果你是新的轨道可能想看看query interface。就个人而言,我喜欢使用squeel宝石,所以我的查询完全是ruby,而不是混合ruby和sql语句。

+0

但这不是代码的目的。我放入OP的代码只是缩短网址的方法的一部分。我将把整个原始方法放在OP中。 – Leahcim

+0

好的。然后我的编辑会照顾你的查询查询 –

+0

谢谢,那么你是说我做错了吗? – Leahcim