I have entries table with a content field which might contain a lot of text. In most cases I don't need to access that field, so it seems to be a big waste of resources to every time load a huge amount of unused data from the database (select * from entries where id = 1).
How could I specify the default_scope, that all the fields apart from content would be loaded from database?
Assuming Rails 3 and a schema that looks like this:
create_table "entries", :force => true do |t|
  t.string   "title"
  t.text     "content"
  t.datetime "created_at"
  t.datetime "updated_at"
end
You can use the select method to limit the fields that are returned like this:
class Entry < ActiveRecord::Base
  default_scope select([:id, :title])
end
In the rails console, you should see something like this:
puts Entry.where(:id => 1).to_sql  # => SELECT id, title FROM "entries"  WHERE "entries"."id" = 1
When you do want to select all of the fields, you can use the unscoped method like this:
puts Entry.unscoped.where(:id => 1).to_sql  # => SELECT * FROM "entries"  WHERE "entries"."id" = 1
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With