Search code examples
ruby-on-railsrubyassociationsmodels

Associations between three models


I have Article model which should have one gallery, and every gallery should have many pictures. Associations between Article-Gallery, Gallery-Picture models work properly, but I have no idea what I'm doing wrong with Article-Picture association. I've attached my code below.

Article.rb model

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

Gallery.rb model

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

Picture.rb model

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

Solution

  • David's answer is right, belongs_to does work for through associations in Rails 4.

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

    The thing to remember is that the through part of a has_one or has_many is referring to an association, not another model. This is important when you're doing trickier associations.