Vinicius Fontoura
Vinicius Fontoura

Reputation: 163

Rails 4 + Postgresql - Joins table with 2 conditions

I need to list Inputs that have Translations with language_id = 1 and dont have Translations with language_id = 2

My current scope is:

scope :language, -> (id){joins(:translations).where('translations.language_id = 1)}

Models:

class Input < ActiveRecord::Base
  has_many :translations
  has_many :languages, through: :translations
  scope :language, -> (id) {joins(:translations).where('translations.language_id = 1')}

  def translation_from_language(language)
    self.translations.where(language: language).take
  end
end

class Translation < ActiveRecord::Base
  belongs_to :input
  belongs_to :language
  before_save :default_values

  #Apenas para testar o scope de search
  scope :search, -> (part) { where("LOWER(value) LIKE ?", "%#{part.downcase}%") }

  # Se nao setar um input manualmente, irá criar um novo
  def default_values
    self.input ||= Input.create
  end
end

class Language < ActiveRecord::Base
  has_many :translations
  has_many :inputs, through: :translations
end

Upvotes: 1

Views: 44

Answers (1)

Hieu Pham
Hieu Pham

Reputation: 6707

So my solution is just create a query like

Input.where("id IN ( SELECT input_id
                     FROM translations
                     WHERE language_id = 1
                   )
             AND id NOT IN (
                     SELECT input_id
                     FROM translations
                     WHERE language_id = 2
                   )")

Upvotes: 2

Related Questions