gpt4 book ai didi

ruby - 通过 has_many 设置我的模型

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:38 25 4
gpt4 key购买 nike

我在尝试使用正确的关联设置我的模型时变得有点不自在,我有如下 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 表是我看到的连接表,它包含我所有的 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 :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 和 image_categories 通过模型中的类别相关联,这不是我认为您想要的。

关于ruby - 通过 has_many 设置我的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34287266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com