привіт хтось тут є?))
Таке питання в мене є три моделі
Category
Categorization
Initiative
Я маю категорію наприклад Category.first
І також в мене в Initiative є певні стейти тобто state
Мені потрібно витягнути всі Initiative
які мають певні стейти тобто state = 'draft' OR state = 'implementing'
Я роблю щось таке
Category.first.categorizations.joins(:initiatives).where("initiatives.state != 'draft' OR initiatives.state != 'rejected' OR initiatives.state != 'locked'")
Проблема в тому що мені повертає Категорію а потрібно всі ініціативи які я в цій категорії і які не мають певні стейти
has_many :through
тобто категорія зєднюється з ініціативою через додаткову модель Categorization
і навборот
також пробую так
Category.first.categorizations.includes(:initiative).where.not(initiative: {state: :draft})
але отримую таку помилку
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "initiative"
LINE 1: ..." WHERE "categorizations"."category_id" = $1 AND ("initiativ...
@bogdan8 Якщо тобі потрібна коллекція ініциаций, то треба якраз на неї і робити запит:
Initiative.where("initiatives.state != 'draft' OR initiatives.state != 'rejected' OR initiatives.state != 'locked'").joins(:categories).where(Category.table_name => { id: 5555 })
краще створити scope-и
########################
# app/models/category.rb
has_many :categorizations, class_name: 'Categorization', foreign_key: :category_id
############################
# app/models/categorization.rb
belongs_to :category, foreign_key: category_id
#########################
# app/models/initiative.rb
has_many :categorizations, foreign_key: categorization_id # треба дивитись які там ключі
scope :not_state, -> (*states) do
where.not(state: states)
end
scope :by_category, ->(id) do
joins(:categorizations).where(Categoryzation.table_name => { category_id: id })
end
приклад
category_id = Category.first.id
my_initiatives = Initiative.not_state(:draft, :rejected, :loched).by_category(category_id)
"has_may through" в данному прикладі не застосовувався, зараз не можу згадаты як там робиться.
@bogdan8 напиши будь ласка як в тебе вийшло.
Category.first.initiatives.where.not(...)
де ".initiatives" змінює класс і всі подальші запиті ".where..." будуть вже на Initiative, яка перед тим вже була фільтровна по category_id
state != draft
draft
але по тій перевірці його не повино бути
Initiative
has_many :categorizations, dependent: :destroy
has_many :categories, through: :categorizations
Categorization
class Categorization < ApplicationRecord
belongs_to :initiative
belongs_to :category
end
Category
has_many :categorizations, dependent: :destroy
has_many :initiatives, through: :categorizations
scope
то запрацювало все як має бути
def self.not_state(*states)
where.not(state: states)
end
def self.by_category(id)
joins(:categorizations).where(Categorization.table_name => { category_id: id })
end
Category.first.initiatives.where_not(state: states)
. Тодi by_category не потрiбен. Один скоуп залишиться. Меньше коду - меньше помилок.
Всем привет :) Надеюсь, тут можно постить вакансии. Принес вот одну Киевско-ремоутовскую (на время карантина). Клиент классный, при желании расскажу больше.
Связь - телеграмм @ljoshalata. Skype - live:oleksiy.lata
О компании:
MCPK - outstaff company that specializes in software development teams creation and augmentation. We connect Ukrainian talents with growing companies, mostly from German-speaking countries. As a developer, you will work directly with the customer as part of his company.
We currently have 50+ teammates in our company. Together with MCPK, you will be surrounded by open-minded experts working with such technologies like Java, PHP, C#, Frontend, Mobile development.
Зарплатная вилка
$2500 - $5500
Тип работы
Full-time
Тип занятости
Office/remote
Описание вакансии:
Currently, we are looking for a Senior Full-stack Developer to work on the development of a forum where users can communicate with each other. Pirate post there some news. The long-term goal to integrate streaming and recording services. Our client is the world's leading provider of rehearsal and recording facilities for artists, with studios in the UK, Germany and the USA.
Задачи:
Требования по позиции:
Условия работы:
Fetching source index from https://rubygems.org/
Retrying fetcher due to error (2/4): Bundler::HTTPError Could not fetch specs from https://rubygems.org/
Retrying fetcher due to error (3/4): Bundler::HTTPError Could not fetch specs from https://rubygems.org/
Retrying fetcher due to error (4/4): Bundler::HTTPError Could not fetch specs from https://rubygems.org/
Could not fetch specs from https://rubygems.org/
ERROR: 17