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