0

如何将自定义属性分配给 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>'
4

2 回答 2

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 => 1}]

于 2013-06-30T10:59:40.913 回答
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
于 2014-10-28T12:50:05.203 回答