Rails:查找数据库记录

时间:2012-09-09 02:04:39

标签: ruby-on-rails

为了提高我对Rails的理解,我正在转换使用data_mapper的Sinatra应用程序。

我试图找到数据映射器的最佳替代品'首先'搜索数据库并返回所搜索记录的第一个实例的方法。

任何人都可以评论这是否正确,或者是否有更好的解决方案?

情况#1 Sinatra

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?

My Rails(with find)

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

原始上下文是一种缩短网址的方法

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

1 个答案:

答案 0 :(得分:0)

您可以在模型上使用验证器。只需在Url模型中执行validates_uniqueness_of :first_name(app / models / url.rb)。 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?

另外,如果您不熟悉rails,可能需要查看query interface。就个人而言,我喜欢使用squeel gem,所以我的查询是严格的ruby而不是混合ruby和sql语句。