ActiveRecord自定义属性

时间:2013-06-30 10:12:10

标签: ruby-on-rails ruby

如何为ActiveRecord模型分配自定义属性? 例如,我可以通过以下方式进行查询:

  select("(CASE WHEN wishlist_items.id IS null THEN 0 ELSE 1 END) AS is_wishlisted_by_me").

这会添加自定义is_wishlisted_by_me属性。但是,如果我已经有一个AR模型的实例并且我想这样做:

model.is_wishlisted_by_me = true

这会返回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>'

2 个答案:

答案 0 :(得分:1)

我认为你可以这样做,在你的模型中定义attr_accessible:

attr_accessible :user_count

r = User.find_by_sql("select count(*) as user_count from users")

puts r.first.user_count

如果哈希会为你做,你可以尝试

User.connection.select_all("select count(*) as user_count from users")

将返回一个哈希数组,如[{:user_count =&gt; 1}]

答案 1 :(得分:0)

这就是我所做的:

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