如何保存和查看与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:列pictures.homepage_item_id不存在
我相信这应该是关于pictures.project_id列。
注意:如果没有在HomepageItem中定义的has_many,则会保存这些项目,但不会创建任何图片。这也是一个Rails 3.2.22项目。
答案 0 :(得分:1)
当你看到它寻找外键时,所以在下面的关联中包含外键,
class HomepageItem < Project
attr_accessible :slug,
:name,
:visible,
:note,
:pictures,
:photo_credit
has_many :pictures, :foreign_key =>:project_id, :order=>:id, :dependent => :destroy