I have a model Enrollment which validates the uniqueness for each course by user:
validates_uniqueness_of :user_id, :scope => :course_id
I created a scope in the Enrollment model where I can pass in the course to narrow down the course by user:
scope :course, lambda { |course| where(:course_id => course.id) }
By doing this, I can call:
current_user.enrollments.course(@course)
However, it then makes me loop through the result, even though there is only one result (unique course for each user). This is fine, but it seems like there should be a way to simply do the scope and then just access the record without need to loop through one result.
Any ideas? I feel like I’m missing something.
Try this:
That will generate SQL query with
LIMIT 1statement and return the model directly without wrapping it into an array.Small note about your scope. As your
Enrollmentmodel hascourseassociation (has_one :courseI assume) you’d better give your scope different name likeby_courseto prevent collision withcourseassociation that allows you to fetch course for a given enrollment.