ActiveRecord::StatementInvalid sometimes when passing a Model as a where parameter #14303

Closed
brodock opened this Issue Mar 6, 2014 · 5 comments

Comments

Projects
None yet
5 participants

brodock commented Mar 6, 2014

I have a really weird error going on, here is the code:

class Account < ActiveRecord::Base
  has_many :entries, :dependent => :restrict_with_exception
...
end
class Entry < ActiveRecord::Base
  belongs_to :account
...
  scope :by_account, lambda { |account| where(account: account) }
  scope :total_value, -> { sum(:value) }
end

Entry.by_account(Account.first).total_value works on my rails console but doesn't while running RSpec tests:

expected no Exception, got #<ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'entries.account' in 'where clause': SELECT SUM(`entries`.`value`) AS sum_id FROM `entries`  WHERE `entries`.`account` = 1> with backtrace:

Here is the output when using rails console:

[1] pry(main)> Entry.by_account(Account.first).total_value
  Account Load (0.2ms)  SELECT `accounts`.* FROM `accounts` ORDER BY `accounts`.`id` ASC LIMIT 1
   (0.2ms)  SELECT SUM(`entries`.`value`) AS sum_id FROM `entries` WHERE `entries`.`account_id` = 2

The issue is that on console (and on production) it understand that I'm talking about "account_id", converts it properly and cast a model.id to get the value, while during the test process it cast model.id but doesn't convert "account" to "account_id".

The issue goes away if I exclude the "total_value" from the query (which will not trigger the calculated attribute).

I'm using Rails 4.0.3

I'm not sure about the conversion issue you talk about, but the scope method is not supposed to return values like AR objects or sums, it must return relations.

Have you tried making that a class method instead? total_value should definitely not be a scope.

brodock commented Mar 6, 2014

@carlosantoniodasilva it was meant to be chained on other queries, but I agree.

the rspec version and code would be helpful to reproduce the bug

Member

senny commented Apr 14, 2014

@brodock please post an executable test-case to reproduce the issue. You can use this script as a starting point.

Member

senny commented Jun 24, 2014

@brodock it's been two months without feedback, I'm going to close this issue.

If you still experience this behavior, please provide some isolated way to reproduce the issue. I'll be happy to reopen and investigate the problem.

Thank you for your understanding.

@senny senny closed this Jun 24, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment