views:

49

answers:

3

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.

+3  A: 

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
John Topley
Yes, and to specify which columns should not be loaded, this should work (untested, though): `default_scope :select => column_names - ['column_to_exclude']).join(', ')`
molf
A: 

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">]
Dan McNevin
A: 

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.

Gary