Я хочу a.items
вернуть все Items
из всех Projects
. Но это ничего не возвращает ... я могу получить детали с a.projects.first.items
, a.projects.second.items
запросов и так далее, но мне не нравится этот подход, чтобы показать отдельные проекты ...Может ли этот тип ассоциации будет построен через has_many: через?
Можно ли создать такую ассоциацию с has_many : хотя (или другие ключевые слова), чтобы возвращать все предметы из всех проектов?
a = Account.first
a.items <---- return nothing via has_many :through
Здесь генерируется SQL для a.items
SELECT "пунктов". * FROM "пунктов" INNER JOIN "проекты" ON "пунктов". "ID" = "проекты". "Item_id" ГДЕ "проекты". "Account_id" =? [[ "account_id", 1]]
Судя по SQL заявления я думаю, что проблема возникает из-за Project
модель имеет item_id
поле. Но это потому, что Project
представляет собой особый тип из Item
.
account.rb
# == Schema Information
#
# Table name: accounts
#
# id :integer not null, primary key
#
class Account < ActiveRecord::Base
has_many :projects
has_many :items, :through => :projects
end
project.rb
# == Schema Information
#
# Table name: projects
#
# id :integer not null, primary key
# account_id :integer
# item_id :integer
#
class Project < ActiveRecord::Base
belongs_to :account
belongs_to :item
has_many :items
end
item.rb
# == Schema Information
#
# Table name: items
#
# id :integer not null, primary key
# name :string
# project_id :integer
#
class Item < ActiveRecord::Base
belongs_to :project
end
Правильно ли сказать проект 'belongs_to' Элемента? Я бы попытался удалить этот incase, это путает Rails. – Kris
Снятие помогло. Благодаря! – yaru