开发者

How can I do Model.find(:except => 'desc') in rails 2.3.x?

The following is a great way to make accessing the database faster by only 'selecting' specified columns on a table:

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

This will find all of the articles and only return the name. Even if it has a body attribute it will complain about it being an undefined attribute because of select.

How would you do :select => 'name' but the reverse; meaning that I want to select everything but the specific column, e.g. ':except =>'. I want to be able to do this:

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

Let me know if this does开发者_StackOverflow社区n't make sense.


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

And then you can use it like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜