2

I have a model which look like this:

class Question < ActiveRecord::Base
  belongs_to :level

    def next
        Question.first(:conditions => ['id > ? AND level_id = ?', self.id, self.level_id], :order => 'id ASC') 
    end

end

This worked perfectly fine, until i updated by rails to version 4.1.0. Now i receive this error:

ArgumentError in QuestionsController#answer invalid value for Integer(): "{:conditions=>[\"id > ? AND level_id = ?\""

I can't figure out how to fix this. is it possibly that the rails update is responsible for this problem? I have exactly the same method in another application and that one still works.

shann
  • 21
  • 2

4 Answers4

4

The method first has changed with Rails 4.

Up to Rails 3.2, it would accept condition arguments, and your implementation would work. Here is the original documentation, notice how it checks the type of *args before using them.

In Rails 4 the method changed (docs), and now it only accepts an integer limit.

You should update your implementation with:

def next
  Question.where('id > ? AND level_id = ?', id, level_id).order(id: :asc).first 
end
tompave
  • 11,952
  • 7
  • 37
  • 63
1

Try this: this should work

Question.where("id > ? AND level_id = ?", id, level_id).order("id asc").first
Raghvendra Parashar
  • 3,883
  • 1
  • 23
  • 36
  • this didn't work unfortunately, it throwed the following error: ActiveRecord::StatementInvalid in QuestionsController#answer SQLite3::SQLException: unrecognized token: "'id > 1 AND level_id = 1) ORDER BY id asc LIMIT 1": SELECT "questions".* FROM "questions" WHERE ('id > 1 AND level_id = 1) ORDER BY id asc LIMIT 1 – shann Apr 30 '14 at 18:44
  • Weird. Can you try it in the console, and add the output to your question? – tompave Apr 30 '14 at 20:17
  • 1
    Also, again in the console, try it with hardcoded values in the SQL statement: `where("id > 1 AND level_id = 1")` – tompave Apr 30 '14 at 20:18
0

Try changing it to

Question.where('id > ? AND level_id = ?', self.id, self.level_id).order(id: :asc).first
j-dexx
  • 10,286
  • 3
  • 23
  • 36
0

From the documentation, the first method takes an integer, not a string.

I don't remember it ever taking a string either, as the method description indicates it returns the first N records. Maybe that particular method was never called until you did an update and did some other changes.

You can use the where method, which takes your conditions, and then use first to get the first result.

Question.where(:conditions => ['id > ? AND level_id = ?', self.id, self.level_id], :order => 'id ASC').first
MxLDevs
  • 19,048
  • 36
  • 123
  • 194