通过 has_many 设置我的模型

Setting up my models with has_many through

我在尝试使用正确的关联设置我的模型时遇到了一些问题,我有 3 个模型如下

class Image < ActiveRecord::Base
  has_many :categories
end

class Category < ActiveRecord::Base
  has_many :image_categories
  has_many :images, through: :image_categories
end

class ImageCategory < ActiveRecord::Base
  # Holds image_id and category_id to allow multiple categories to be saved per image, as opposed to storing an array of objects in one DB column
  belongs_to :image
  belongs_to :category
end

ImageCategory table 是我看到的连接 table,它包含我所有的 image_ids 及其对应的 category_ids,作为 Image可以有多个Categories

创建图像的表单

permit_params :id, :title, :description, :photo,
            category_ids: []
form html: { multipart: true } do |f|
  inputs do
    f.semantic_errors
    f.input :title
    f.input :description, as: :text, input_html: { rows: 10, cols: 10 }
    f.input :categories, as: :check_boxes
  end
end

当我尝试创建 image 时,出现以下错误:

can't write unknown attribute `image_id`

我在这里犯了什么错误?

如我所见,图像模型中存在错误

class Image < ActiveRecord::Base
  has_many :categories, through: :image_categories
  has_many :image_categories
end

希望对你有帮助!!!

我认为您设置关联的方式导致了这个问题。

class Image < ActiveRecord::Base
  has_many :image_categories
  has_many :categories, through: :image_categories
end

class Category < ActiveRecord::Base
  has_many :image_categories
  has_many :images, through: :image_categories
end

class ImageCategory < ActiveRecord::Base
  belongs_to :image
  belongs_to :category
end

您当前的关联描述的是,一个类别可以通过 image_categories 包含许多图像,但是图像和 image_categories 通过模型中的类别相关联,这不是我认为您想要的。

补充一下,在这种情况下不需要您的连接模型 ImageCategory。查看 has_and_belongs_to_many 协会 (HABTM)。

has_many:through 在需要向 ImageCategory 模型添加除 ImageIdCategoryId.

之外的其他属性的情况下很有用

但是,在您的情况下,HABTM 就足够了。