2011-06-14 22 views
2

以下是使訪問數據庫只「選擇」指定的列更快桌子上的一個偉大的方式:如何在rails 2.3.x中使用Model.find(:except =>'desc')?

Article.find(:all, :select => 'name') 

這會發現所有的文章,只返回名稱。即使它具有body屬性,它也會因爲select而抱怨它是未定義的屬性。

你會怎麼做:select => 'name'但相反;這意味着我想選擇除特定列之外的所有內容,例如':除了=>'。我想能夠做到這一點:

Article.find(:all, :except => 'body') 

讓我知道如果這沒有意義。

+0

我從來沒有在這之前,也許你可以循環所有的列和選擇的一切,但你作爲參數傳遞列? – apneadiving 2011-06-14 23:26:10

+0

這部分只是self.columns - ':除了'我只是不確定其他部分。 – s84 2011-06-14 23:36:22

+2

你可以這樣做: 'Article.find(:all,:select =>(Article.columns - ['body']))' – 2011-06-15 07:16:36

回答

1
def find_with_except(*args) 
    options = args.extract_options! 
    raise "Find accepts select or except but not both." if options[:except] && options[:select] 
    if options[:except] 
    formated_options = Array(options.delete(:except)).map!(&:to_s) 
    options[:select] = (Article.column_names - formated_options).join(", ") 
    find_without_except(*(args << options)) 
    else 
    find_without_except(*(args << options)) 
    end 
end 
alias_method_chain :find, :except 

然後你就可以使用它像這樣:

Model.find(:all, :except => 'body')