Vinicius Fontoura Vinicius Fontoura - 7 months ago 20
Ruby Question

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


This is what im trying to create: 152.236.102.18:3000/images/explicacao.png

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

Answer

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)) }