I have a function that I want to write and cannot work out how it will work. The first line returns my steps in the order that they should be, and the second line I want to return the last matching step in all the steps for the course. I think I am close but need to know what I’ve done wrong.
course_steps_in_order = course.steps.sort_by(&:component_and_step_order)
last_completed_step = current_user.completed_steps.where("steps.id in ?", course_steps_in_order).last
I am getting the error…
ActiveRecord::StatementInvalid: PG::Error: ERROR: syntax error at or near "1"
LINE 1: ... WHERE "user_steps"."user_id" = 3 AND (step.id in 1,2,4,8,5,...
^
: SELECT "steps".* FROM "steps" INNER JOIN "user_steps" ON "steps"."id" = "user_steps"."step_id" WHERE "user_steps"."user_id" = 3 AND (step.id in 1,2,4,8,5,3,7,6,9) ORDER BY "steps"."id" DESC LIMIT 1
A course has many components which has many steps, as per the below models…
class Course < ActiveRecord::Base
has_many :components, :dependent => :destroy, :order => "component_order"
has_many :steps, :through => :components, :dependent => :destroy
end
class Component < ActiveRecord::Base
belongs_to :course
has_many :steps, :dependent => :destroy, :order => "step_order"
end
class Step < ActiveRecord::Base
belongs_to :component
def component_and_step_order
component_order * 100 + step_order
end
end
Add the collection-enclosing parenthesis:
Now the query will generate correctly like so: