我有两个带有has_many关联的模型,如下所示。我的问题是,我无法得到任何一个保存的ID。我在站点表中有一个model_id,在模型表中有一个site_id来保存id。我错过了这些协会还是做错了什么?
class Site < ActiveRecord::Base
has_many :models
end
class Model < ActiveRecord::Base
has_many :sites
end
答案 0 :(得分:2)
class Site < ActiveRecord::Base
has_many :model_sites, inverse_of: :site, dependent: :destroy
has_many :models, through: :model_sites
end
class ModelSite < ActiveRecord::Base
belongs_to :model
belongs_to :site
validates_presence_of :model, :site
end
class Model < ActiveRecord::Base
has_many :model_sites, inverse_of: :model, dependent: :destroy
has_many :sites, through: :model_sites
end