ruby on rails - ActiveRecord: scope with a lambda applied on top of has_many Error -


i have 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 type following in console 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 `+' #<user:0x00000007d7d528>     /home/augustin/.rvm/gems/ruby-2.1.4/gems/activemodel-3.2.21/lib/active_model/attribute_methods.rb:407:in `method_missing'     /home/augustin/.rvm/gems/ruby-2.1.4/gems/activerecord-3.2.21/lib/active_record/attribute_methods.rb:149:in `method_missing'     /home/augustin/.rvm/gems/ruby-2.1.4/gems/activesupport-3.2.21/lib/active_support/core_ext/array/access.rb:19:in `to'     /home/augustin/.rvm/gems/ruby-2.1.4/gems/activerecord-3.2.21/lib/active_record/associations/collection_proxy.rb:91:in `method_missing'     (irb):14     /home/augustin/.rvm/gems/ruby-2.1.4/gems/railties-3.2.21/lib/rails/commands/console.rb:47:in `start'     /home/augustin/.rvm/gems/ruby-2.1.4/gems/railties-3.2.21/lib/rails/commands/console.rb:8:in `start'     /home/augustin/.rvm/gems/ruby-2.1.4/gems/railties-3.2.21/lib/rails/commands.rb:41:in `<top (required)>'     script/rails:40:in `require'     script/rails:40:in `<main>' 

and craziest thing that:

user.first.transactions.active.owner(user.first) 

works!!

i'm using rails 3.2 pretty old know, still, annoying, right?

questions are:

  • shouldn't user.first.transactions.class activerecord::relation?
  • why error occurs @ user.first.transactions.owner(user.first)? activerecord bug or doing wrong?

  1. rails console special associations, "load" them turned arrays.

  2. i think might have naming clash. have associations user , owner , define scopes same names. use class methods, opt little more meaningful names (avoiding name clash).

so write like:

 def self.from_user(user)    where(user_id: user.id)  end   def self.owned_by(user)    where(owner_id: user.id)  end 

i not sure cause of error naming or because use scope method.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -