gpt4 book ai didi

ruby-on-rails - 三个模型之间的关联

转载 作者:太空宇宙 更新时间:2023-11-03 17:22:04 25 4
gpt4 key购买 nike

我有一个 Article 模型,它应该有一个画廊,每个画廊应该有很多图片。 Article-Gallery、Gallery-Picture 模型之间的关联工作正常,但我不知道我在 Article-Picture 关联方面做错了什么。我在下面附上了我的代码。

Article.rb 模型

class Article < ActiveRecord::Base  
belongs_to :gallery
has_many :pictures, through: :galleries
end

Gallery.rb 模型

class Gallery < ActiveRecord::Base
has_many :pictures, dependent: :destroy
has_many :articles
end

Picture.rb 模型

class Picture < ActiveRecord::Base
belongs_to :gallery
has_many :articles, through: :galleries
end

Schema.rb

ActiveRecord::Schema.define(version: 20150829181617) do

create_table "articles", force: :cascade do |t|
t.string "title"
t.text "content"
t.integer "author_id"
t.integer "language_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "gallery_id"
end

add_index "articles", ["gallery_id"], name: "index_articles_on_gallery_id"

create_table "galleries", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

create_table "pictures", force: :cascade do |t|
t.string "image"
t.integer "gallery_id"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end

最佳答案

在 Rails 4 中,您当然可以声明文章:

belongs_to :gallery
has_many :pictures, :through => :gallery

...还有那张图片...

belongs_to :gallery
has_many :articles, :through => :gallery

...允许您同时执行这两项操作:

@picture.articles

...和...

@article.galleries

...这两个都作为通过画廊表加入的单个查询执行。

关于ruby-on-rails - 三个模型之间的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32289621/

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