三种模型之间的关联

时间:2015-08-29 18:50:22

标签: ruby-on-rails ruby associations models

我有文章模型应该有一个画廊,每个画廊应该有很多图片。 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

2 个答案:

答案 0 :(得分:4)

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

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

......那张照片......

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

......允许你同时做两件事:

@picture.articles

......和......

@article.galleries

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

答案 1 :(得分:2)

David的回答是正确的,belongs_to适用于Rails 4中的through个关联。

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

要记住的是,throughhas_one的{​​{1}}部分指的是关联,而不是指另一个模型。当你进行棘手的关联时,这很重要。