从 Rails 中的多个 has_many 关系级别检索记录
Retrieve records from multiple levels of has_many relationships in Rails
组织有很多项目。项目有很多网站。如何使用 Rails 4 获取特定组织的所有网站?
您可以使用以下方法检索所有网站:
@websites = Website.includes(:project => :organizations).where(["organization.id = ?", params[:organization]])
确保 params[:organization]
是您要获取其所有网站的组织的实际 ID。
您也可以使用 has_many :through association。这样,您将能够通过简单的 @organization.websites
.
获取所有网站
A has_many :through association is often used to set up a many-to-many
connection with another model. This association indicates that the
declaring model can be matched with zero or more instances of another
model by proceeding through a third model. For example, consider a
medical practice where patients make appointments to see physicians.
The relevant association declarations could look like this:
组织有很多项目。项目有很多网站。如何使用 Rails 4 获取特定组织的所有网站?
您可以使用以下方法检索所有网站:
@websites = Website.includes(:project => :organizations).where(["organization.id = ?", params[:organization]])
确保 params[:organization]
是您要获取其所有网站的组织的实际 ID。
您也可以使用 has_many :through association。这样,您将能够通过简单的 @organization.websites
.
A has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this: