三个模型之间的关联

Associations between three models

我有一个 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

David 的回答是正确的,belongs_to 对 Rails 中的 through 协会有效 4.

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

要记住的是 has_onehas_manythrough 部分指的是 关联 ,而不是另一个 型号。当您进行更棘手的关联时,这很重要。

在Rails4中你当然可以声明一篇文章:

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

...还有那张照片...

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

...允许您同时执行以下操作:

@picture.articles

...和...

@article.galleries

... 这两个都作为单个查询执行,通过画廊 table.