سؤال

I'm creating a UserSession model for my application, with a scope active for sessions active in the last week.

Everything is working correctly up to my attempts to use the application after logging in - I am able to log in and create a session, and it's able to find my user by user_id. However, Rails is generating SQL that returns no sessions, so I can't actually use the application.

This is the relevant code of the model:

scope :active, -> { where('accessed_at >= ?', 2.weeks.ago) 

def self.authenticate(key)
    self.active.find_by(key: key)
end

And this is the generated SQL when I call UserSession.authenticate('123345')

SELECT  `user_sessions`.* FROM `user_sessions`  WHERE `user_sessions`.`key` = '123345' AND (accessed_at >= '2013-10-12 10:50:52') LIMIT 1

As shown above, it wraps the conditions from the scope lambda in parentheses, which makes the SQL valid but not returning the necessary data. Is there any way to make the scope without parentheses?

هل كانت مفيدة؟

المحلول

The generated SQL is semantically correct. Rails wraps each level of scope in its own set of parenthesis in order to ensure correct execution order.

There is no difference between the following when executed:

SELECT  `user_sessions`.* FROM `user_sessions` WHERE `user_sessions`.`key` = '123345' AND (accessed_at >= '2013-10-12 10:50:52') LIMIT 1

and

SELECT  `user_sessions`.* FROM `user_sessions`  WHERE `user_sessions`.`key` = '123345' AND accessed_at >= '2013-10-12 10:50:52' LIMIT 1

Are you sure that there is a record that satisfies that query?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top