通过 STI 将 has_many 与多种模型类型结合使用
Using has_many with Multple Model Types via STI
如何保存和查看与通过 STI 继承的 2 个不同模型的 has_many 关系?
我有一个项目的基本模型如下:
class Project < ActiveRecord::Base
attr_accessible :slug,
:category_id,
:description,
:name,
:visible,
:note,
:contractor, :contractor_url,
:date_complete, :architect, :architect_url,
:building_year,
:project_type,
:address, :city, :state, :country,
:pictures,
:photo_credit
has_many :pictures, :order=>:id, :dependent => :destroy
Picture.rb:
class Picture < ActiveRecord::Base
attr_accessible :project_id, :image, :caption, :cover, :dimensions
belongs_to :project
并且使用 STI 我有主页项目,它显示项目的一个子集并且特定于主页:
class HomepageItem < Project
attr_accessible :slug,
:name,
:visible,
:note,
:pictures,
:photo_credit
has_many :pictures, :order=>:id, :dependent => :destroy
这会导致出现错误,需要在图片上添加新列 homepage_item_id
而不是 project_id
PG::UndefinedColumn: ERROR: column pictures.homepage_item_id does not exist
I believe this should be looking on the pictures.project_id column.
注意:如果没有在 HomepageItem 中定义 has_many,则会保存项目,但不会创建图片。这也是一个 Rails 3.2.22 项目。
如您所见,它正在寻找外键,因此在关联中包含外键,如下所示,
class HomepageItem < Project
attr_accessible :slug,
:name,
:visible,
:note,
:pictures,
:photo_credit
has_many :pictures, :foreign_key =>:project_id, :order=>:id, :dependent => :destroy
如何保存和查看与通过 STI 继承的 2 个不同模型的 has_many 关系?
我有一个项目的基本模型如下:
class Project < ActiveRecord::Base
attr_accessible :slug,
:category_id,
:description,
:name,
:visible,
:note,
:contractor, :contractor_url,
:date_complete, :architect, :architect_url,
:building_year,
:project_type,
:address, :city, :state, :country,
:pictures,
:photo_credit
has_many :pictures, :order=>:id, :dependent => :destroy
Picture.rb:
class Picture < ActiveRecord::Base
attr_accessible :project_id, :image, :caption, :cover, :dimensions
belongs_to :project
并且使用 STI 我有主页项目,它显示项目的一个子集并且特定于主页:
class HomepageItem < Project
attr_accessible :slug,
:name,
:visible,
:note,
:pictures,
:photo_credit
has_many :pictures, :order=>:id, :dependent => :destroy
这会导致出现错误,需要在图片上添加新列 homepage_item_id
而不是 project_id
PG::UndefinedColumn: ERROR: column pictures.homepage_item_id does not exist
I believe this should be looking on the pictures.project_id column.
注意:如果没有在 HomepageItem 中定义 has_many,则会保存项目,但不会创建图片。这也是一个 Rails 3.2.22 项目。
如您所见,它正在寻找外键,因此在关联中包含外键,如下所示,
class HomepageItem < Project
attr_accessible :slug,
:name,
:visible,
:note,
:pictures,
:photo_credit
has_many :pictures, :foreign_key =>:project_id, :order=>:id, :dependent => :destroy