heartcombo/has_scope

Have a issue using this with a user relation

kairos0ne opened this issue · 2 comments

In my model I have:

scope :by_server, -> user { where(user: user) }

It seems to work at face value but it returns nothing at all for any query.

Strangely enough, in the same model I have another relation `belongs_to :table``

and I'm using this scope :by_table, -> table { where(table: table) }

That scope works perfectly but when I try with the user relation it always searches for user with id = 0 There is no user with id = 0 so it returns no orders.

Here are my scopes in the model:

 scope :ordered_by_date, -> { order(created_at: :asc) }

 scope :reciepted, -> { where(reciepted: true) }

 scope :not_reciepted, -> { where(reciepted: false) }

 scope :quoted, -> { where(quoted: true) }

 scope :not_quoted, -> { where(quoted: false) }

 scope :by_table, -> table { where(table: table) }

 scope :preparing, -> { where(workflow_state: "preparing", paid: false) }

 scope :by_server, -> user { where(user: user) }

Here is my controller index action:

 # GET /orders
      def index
        @orders = apply_scopes(@orders)
        if params[:page] && params[:per_page]
          paginated_response(@orders, params)
        else
          render json: @orders, each_serializer: OrderListSerializer
        end
      end

Used this instead.
scope :by_server, -> (user) { joins(:user).where('users.name in (?)', user)}

A scope with a condition based on a relation like where(user: user) would only work if passing in the user id as "user" there via params. It certainly depends on what you're trying to achieve, but it seems you've got it figured out by searching the user name. 👍