简体   繁体   中英

Rails named scopes

I was trying to refactoring and optimizing me code. In particular, I wanted to reduce the amount of queries going to the database. In my users controller it worked very well but in an other controller, where I tried the same, it didn't. I've searched for some time now for the answer why it didn't work but I can't really answer it.

I've got users, which can subscribe to courses through enrolments. They are connected through has_many :through etc. relationships. The following works:

@users_courses = current_user.courses
@courses = @users_courses.a_named_scope

But in my courses controller the following wont work:

@all_courses = Course.all
@specific_course = @all_courses.specific_course_scope

The scopes are defined in the respective models and work properly. They are not complicated, just "where ... true/false" definitions. Does someone know the problem here? Thanks!

I'm using rails version 3.2 and ruby version 2.

Until Rails 4 you should use scoped method if you want to have ActiveRecord::Relation instance (on which you can call other scopes) returned instead of Array :

@all_courses = Course.scoped
@specific_course = @all_courses.specific_course_scoped

This should work.

If you want to use includes(:courses) , you just do it, for example with:

@specific_course = @all_courses.specific_course_scoped.includes(:courses)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM