Search code examples
ruby-on-rails-3scopehas-manynamed-scopedefault-scope

Best way to scope a has_many relationship when find()'ing the parent object


I'm struggling a bit with understanding default scopes and named scopes with my quiz application. I'm on rails 3.0.

I have a Question model that has_many UserResponse models.

Question has the question text and possible answer_ids. UserResponse ties user_id to a question_id and answer_id.

When I find() a Question to display to the user, I don't want to also pull every single UserResponse. By default, I'd like to only pull the UserResponse for the current user_id to see if they have already answered this question.

How can I create a scope on either the Question or UserResponse to accomplish this?


Solution

  • Not sure about the scope but I would start out just using the model relationships with something like this query perhaps:

    (given question and user)

    responses = question(question).user_responses(user)
    

    Then once working ok I would move onto scopes (if needed) and have:

    a scope on the user model for response

    (Rails3 syntax)  scope :responses_by_user,  labmda { join(:responses) }
    

    a scope on the question model for responses

    (Rails3 syntax)  scope :responses_by_question,  labmda { join(:responses) }  
    

    Note: I leaning more towards these 'join' approaches in the thought that they will only do 'inner' joins, i.e. only return rows where response records do exist. I am doing this as opposed to a syntax more like lambda { where ('user_id = ?', User.id) } Then you could also chain them together. Something like Question.responses_by_question(question).responses_by_user(user)`