SinGar
SinGar

Reputation: 111

How to convert a method into a scope.

Hello I am trying to convert the method self.liked_by(user) into a scope. I am not entirely sure what my instructor is asking for so any interpretations on the question are greatly appreciated.

this is the method in question that I am supposed to turn into a scope.

def self.liked_by(user)
    joins(:likes).where(likes: { user_id: user.id })
end

this is where the method appears in the model

class Bookmark < ActiveRecord::Base
  belongs_to :user
  belongs_to :topic
  has_many :likes, dependent: :destroy
  before_validation :httpset
  validates :url, format: { with: /\Ahttp:\/\/.*(com|org|net|gov)/i,
    message: "only allows valid URLs." }

  def self.liked_by(user)
    joins(:likes).where(likes: { user_id: user.id })
  end

  def  httpset
    if self.url =~ /\Ahttp:\/\/|\Ahttps:\/\//i
    else
      if self.url.present?
        self.url = "http://"+ self.url
      else
        self.url = nil
      end
    end
  end
end

And this is where the method is called in the controller

class UsersController < ApplicationController
  def show
    user = User.find(params[:id])
    @bookmarks = user.bookmarks
    @liked_bookmarks = Bookmark.liked_by(user)
  end
end

Thanks for looking at my problem and have a good day.

Upvotes: 0

Views: 198

Answers (2)

Sravan
Sravan

Reputation: 18647

@liked_bookmarks = Bookmark.liked_by(user)

In this line, in the same way you send the user parameter to a method, the same way you can send it to a scope.

class Bookmark < ActiveRecord::Base
   ---------
   ---------
   scope :liked_by, ->(user) { joins(:likes).where(likes: { user_id: user.id }) }
   ---------
   ---------
  end 

the parameter you sent from the scope call can be accessed using the (user{or any name) in the scope

reference of scopes

Upvotes: 3

Uzbekjon
Uzbekjon

Reputation: 11813

As Owen suggested, read the docs to understand what scopes are. It is just another syntax to define your model's class methods (just like the one you already have).

scope :liked_by, ->(user) { joins(:likes).where(likes: { user_id: user.id }) }

Upvotes: 2

Related Questions