这种类型的关联可以通过 has_many :through 建立吗?
Can this type of association be built via has_many :through?
我想要 a.items
到 return 所有 Items
从所有 Projects
。
但它 return 没什么...
我可以通过 a.projects.first.items
、a.projects.second.items
查询等获取项目,但我不喜欢这种列出单个项目的方法...
是否可以通过 has_many :though (或其他关键字)与 return 所有项目的所有项目建立这种关联?
a = Account.first
a.items <---- return nothing via has_many :through
这是为 a.items
生成的 SQL
SELECT "items".* FROM "items" INNER JOIN "projects" ON "items"."id" =
"projects"."item_id" WHERE "projects"."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 依赖项后 <--> 项目代码开始按我想要的方式工作。
这是工作代码:
class Project < ActiveRecord::Base
belongs_to :account
# belongs_to :item <---- Comment this line
has_many :items
end
我想要 a.items
到 return 所有 Items
从所有 Projects
。
但它 return 没什么...
我可以通过 a.projects.first.items
、a.projects.second.items
查询等获取项目,但我不喜欢这种列出单个项目的方法...
是否可以通过 has_many :though (或其他关键字)与 return 所有项目的所有项目建立这种关联?
a = Account.first
a.items <---- return nothing via has_many :through
这是为 a.items
SELECT "items".* FROM "items" INNER JOIN "projects" ON "items"."id" = "projects"."item_id" WHERE "projects"."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 依赖项后 <--> 项目代码开始按我想要的方式工作。
这是工作代码:
class Project < ActiveRecord::Base
belongs_to :account
# belongs_to :item <---- Comment this line
has_many :items
end