in ActiveRecord::Relation, is it preferable to scope by parent in the model or set @parent in the controller

71 Views Asked by At

I have a class which belongs to another.

course.rb

class Course < ActiveRecord::Base
belongs_to :school

I currently use a before_action to set the parent instance in the controller.

courses_controller.rb

class CoursesController < ApplicationController

  #returns @school. only: [methods] avoids trying to set @school when no school param expected
  before_action :set_school, only: [:index]

  def index
    @courses = if @school.nil?
      Course.where(user_id: current_user.id)
    else
      Course.where(user_id: current_user.id, school_id: @school.id)
    end
  end

  private

    def set_school
      if params[:school_id]
        @school = School.find params[:school_id]
      end
    end

...But I'm seeing the scope method in models and wondering if it would be more appropriate to simply set a default scope of :school in the model and unscope/rescope in those rare occasions where I want to index by user and not school.

Full disclosure: I've only noticed a model scoped by parent in an example using the acts_as_list gem, which I don't plan to use, but it seems likely that Rails would allow it.

Is this possible AND more appropriate? I am coming to favor the skinny model approach, but it is only one line vs. 6 (in the controller).

1

There are 1 best solutions below

0
On BEST ANSWER

Not sure whether it's possible, but it will couple most of your app to the default_scope implementation, which IMHO is a very bad idea. You might end up needing to change this implementation down the line, which is going to have pretty high impact. It will also make your unit tests more convoluted.

More lines of code isn't necessarily a bad thing if it helps you maintain good separation of concerns.