Vinicius Fontoura
Vinicius Fontoura

Reputation: 163

Ruby on Rails Scope

I'm creating a sticker album and i need to scope repeated stickers. I still can't fully understand scopes in rails. How can i create a scope that gets all the repeated stickers from a user?

Figurinha has a colada boolean attribute, which means the sticker is placed or not in the album.

Dep is the players database, Figurinha get the name, avatar and others infos from Dep model.

repetida is the method I was trying to create to check if the figurinha is repeated or not.

A figurinha is repeated when Figurinha has another record with the same user and dep wich is already been colada

User.rb

class User < ActiveRecord::Base
  has_many :figurinhas
end

Figurinha.rb

class Figurinha < ActiveRecord::Base
  belongs_to :user
  belongs_to :dep

  def repetida
    coladas = self.user.figurinhas.where(colada: true)
    colodas.map{|a| a.dep}.include?(self.dep)
  end

end

Dep.rb

class Dep < ActiveRecord::Base
  has_attached_file :avatar
  validates_attachment_content_type :avatar, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]

  belongs_to :partido, foreign_key: :partido, primary_key: :sigla

  def avatar_from_url(url)
    self.avatar = open(url)
  end
end

Upvotes: 0

Views: 443

Answers (2)

Abdoo Dev
Abdoo Dev

Reputation: 1276

If figurinha can only have one true colada per user you can try this :

scope :repetida, ->(user_id) { uniq.where(user_id: user_id, colada: false, dep_id: Figurinha.where(user_id: user_id, colada: true).pluck(:dep_id)) }

Upvotes: 1

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

Replace

def repetida
  coladas = self.user.figurinhas.where(colada: true)
  colodas.map{|a| a.dep}.include?(self.dep)
end

with:

scope :repetida, ->(user_id) {where(user_id: user_id).group(:dep_id).having("count(*) > 1").having("bool_or(colada) =true") }

and call should be:

Figurinha.repetida(User.first.id)

which is trying to select all Figurinha which belongs to user_id and then grouping them with dep_id so we now have groups of repeated Figurinha but we only need if the count of the group is > 1 to consider a duplicate.

Upvotes: 1

Related Questions