Reputation: 21553
How can I assign a custom attribute to an ActiveRecord model? For example, I can do it when querying via:
select("(CASE WHEN wishlist_items.id IS null THEN 0 ELSE 1 END) AS is_wishlisted_by_me").
This adds a custom is_wishlisted_by_me
attribute. But what if I already have an instance of an AR model and I want to do:
model.is_wishlisted_by_me = true
this returns a NoMethodError: undefined method
NoMethodError: undefined method `is_wishlisted_by_me=' for #<SIImage:0x007fc8c41c7ef8>
from /Users/Test/.rvm/gems/ruby-1.9.3-p327/gems/activemodel-3.2.13/lib/active_model/attribute_methods.rb:407:in `method_missing'
from /Users/Test/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-3.2.13/lib/active_record/attribute_methods.rb:149:in `method_missing'
from (irb):8
from /Users/Test/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /Users/Test/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /Users/Test/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Upvotes: 0
Views: 2757
Reputation: 12011
This is what I've done:
after_initialize do
self.is_wishlisted_by_me = nil unless @attributes.key?("is_wishlisted_by_me")
end
def is_wishlisted_by_me
@attributes["is_wishlisted_by_me"]
end
def is_wishlisted_by_me=(value)
@attributes["is_wishlisted_by_me"] = value
end
Upvotes: 0
Reputation: 1055
I think you can do it with this way, define attr_accessible in your model:
attr_accessible :user_count
r = User.find_by_sql("select count(*) as user_count from users")
puts r.first.user_count
If a hash will do for you, you may try
User.connection.select_all("select count(*) as user_count from users")
which will return an array of hash like [{:user_count => 1}]
Upvotes: 1