Anna
Anna

Reputation: 1459

Is it possible to specify columns that should not be loaded in ActiveRecord?

I've got a database table that is shared with another application. It has many columns that I will never use in my application. Is it possible to specify columns to be ignored in the ActiveRecord model?

Usually it's not too big of a deal, but in this case I've got a table with two blobs that I'll never need joined with another table that has 37 columns (of which I need one).

I suppose I could settle for always using the :select attribute in my finds and associations, but I'd like to just configure it once.

Upvotes: 1

Views: 188

Answers (3)

Gary Myers
Gary Myers

Reputation: 35401

You could use a view in the database rather than look at the source tables directly. This has the advantage that you don't have to change the code if they add another BLOB column as it wouldn't be in the view (unless you change the view) and so wouldn't be picked up.

Upvotes: 0

Dan McNevin
Dan McNevin

Reputation: 22336

You could hack this together with a named_scope

  named_scope :without, lambda {|arg| {:select =>Post.column_names.reject {|c| [arg].flatten.include? c.to_sym}.join(",")} }

>> Post.column_names
=> ["id", "title", "body", "test1", "test2", "created_at", "updated_at"]
>> Post.without(:test1)
  Post Load (0.4ms)   SELECT id,title,body,test2,created_at,updated_at FROM "posts" 
=> [#<Post id: 1, title: "test post", body: "something something", test2: "test2 thing", created_at: "2010-01-11 17:11:41", updated_at: "2010-01-11 17:11:41">]
>> Post.without([:test1,:body])
  Post Load (0.3ms)   SELECT id,title,test2,created_at,updated_at FROM "posts" 
=> [#<Post id: 1, title: "test post", test2: "test2 thing", created_at: "2010-01-11 17:11:41", updated_at: "2010-01-11 17:11:41">]

Upvotes: 1

John Topley
John Topley

Reputation: 115362

I think you should be able to specify a default_scope for your model, passing a :select that specifies the columns that you're interested in.

class MyModel < ActiveRecord::Base
  default_scope :select => 'column1, column2, column3'
end

Upvotes: 3

Related Questions