I have the following code:
class User < ActiveRecord::Base
has_many :transactions
end
class Transaction < ActiveRecord::Base
belongs_to :user
belongs_to :owner, class_name: 'User'
scope :user, ->(user) { where('user_id = ?', user.id) }
scope :owner, ->(user) { where('owner_id = ?', user.id) }
scope :active, where(is_active: true)
end
If I type the following in the console I have:
Transaction.user(User.first).class # ActiveRecord::Transaction OK
User.first.transactions.class # Array KO
User.first.transactions.active.class # ActiveRecord::Transaction OK
User.first.transactions.where(used_id: User.first.id).class # ActiveRecord::Transaction OK
User.first.transactions.owner(User.first) # ERROR:
NoMethodError: undefined method `+' for #<User:0x00000007d7d528>
from /home/augustin/.rvm/gems/ruby-2.1.4/gems/activemodel-3.2.21/lib/active_model/attribute_methods.rb:407:in `method_missing'
from /home/augustin/.rvm/gems/ruby-2.1.4/gems/activerecord-3.2.21/lib/active_record/attribute_methods.rb:149:in `method_missing'
from /home/augustin/.rvm/gems/ruby-2.1.4/gems/activesupport-3.2.21/lib/active_support/core_ext/array/access.rb:19:in `to'
from /home/augustin/.rvm/gems/ruby-2.1.4/gems/activerecord-3.2.21/lib/active_record/associations/collection_proxy.rb:91:in `method_missing'
from (irb):14
from /home/augustin/.rvm/gems/ruby-2.1.4/gems/railties-3.2.21/lib/rails/commands/console.rb:47:in `start'
from /home/augustin/.rvm/gems/ruby-2.1.4/gems/railties-3.2.21/lib/rails/commands/console.rb:8:in `start'
from /home/augustin/.rvm/gems/ruby-2.1.4/gems/railties-3.2.21/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:40:in `require'
from script/rails:40:in `<main>'
And the craziest thing is that:
User.first.transactions.active.owner(User.first)
Works!!
I'm using Rails 3.2 so pretty old I know, but still, annoying, right?
Questions are:
- Shouldn't
User.first.transactions.class
be anActiveRecord::Relation
? - Why does the error occurs at
User.first.transactions.owner(User.first)
? Is it an ActiveRecord bug or am I doing something wrong?
Aucun commentaire:
Enregistrer un commentaire