Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: prevent from selecting a column by default

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?

like image 825
krn Avatar asked Jun 16 '11 09:06

krn


1 Answers

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
like image 94
phlipper Avatar answered Nov 14 '22 22:11

phlipper