Rails复杂关联

时间:2016-03-11 16:43:37

标签: ruby-on-rails ruby-on-rails-4

我有这个型号:

class Product < ActiveRecord::Base
  has_many :feature_products, -> { where("taxonomy_slug = feature_taxonomy_slug") }
  has_many :features, through: :feature_products, class_name: "Feature", source: :feature
end

class Feature < ActiveRecord::Base
  has_many :feature_products, -> (object){ where(" feature_taxonomy_slug = ?", object.taxonomy_slug) }, primary_key: :external_id
  has_many :products, through: :feature_products
end

class FeatureProduct < ActiveRecord::Base
  belongs_to :product
  belongs_to :feature, primary_key: :external_id
end

,表格如下:

  create_table "feature_products", force: :cascade do |t|
     t.integer "product_id"
     t.integer "feature_id"
     t.string  "feature_taxonomy_slug"
  end

  create_table "features", force: :cascade do |t|
     t.integer "external_id"
     t.string  "name"
     t.string  "taxonomy_slug"
  end

  create_table "products", force: :cascade do |t|
     t.integer  "company_id"
  end

我希望能够像这样创建功能产品协会:

feature = Feature.create(external_id: 1234, name: 'WS', taxonomy_slug: 'prop')
Product.create(name: 'XXX', features: [feature])

问题是表feature_products,它存储id但它不存储feature中的feature_taxonomy_slug。有没有办法存储它?

1 个答案:

答案 0 :(得分:0)

我认为如果您想在FeatureProduct模型中保存slug,那么您将必须明确创建一个,即

FeatureProduct.create(product: product, feature: feature, feature_taxonomy_slug: feature.taxonomy_slug)

我不明白为什么要在FeatureProduct模型中保存slug。 您是否有理由不想通过product.features协会访问它?