Search code examples
ruby-on-railsassociationsmodels

Rails - How to associate models in one direction only


Ahoy guys,

I'm new to Rails, and I feel like I'm definitely missing something crucial here, because it seems like this should be an easily solvable problem.

I've set up a Page model and a Coord model (with help from the getting started tutorial), and Coord successfully belongs_to Page. I'm trying to apply similar logic to make another model, Comment, belong to Coord, and only belong to Page via Coord.

Do I use :through for an association that (I think) only needs to link in one direction? As in Page < Coord < Comment? At the moment I have:

class Page < ActiveRecord::Base
  attr_accessible :description, :name
  has_many :coords
  has_many :comments, :through => :coords
end

Coord model:

class Coord < ActiveRecord::Base
  belongs_to :page
  has_many :comments
  attr_accessible :coordinates, :x, :y
  validates :x, :presence => true
  validates :y, :presence => true
end

Then the Comment model:

class Comment < ActiveRecord::Base
  belongs_to :coord
  belongs_to :page
  attr_accessible :body
end

I still keep getting errors about comments being an undefined method, or an association not being defined. Apologies if this is a common question, I don't personally know anyone who knows Rails, and the documentation only has examples too far removed from mine (to my knowledge). Thanks

Edit: added DB schema

ActiveRecord::Schema.define(:version => 20120712170243) do

  create_table "comments", :force => true do |t|
    t.text     "body"
    t.integer  "coord_id"
    t.integer  "page_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  add_index "comments", ["coord_id"], :name => "index_comments_on_coord_id"
  add_index "comments", ["page_id"], :name => "index_comments_on_page_id"

  create_table "coords", :force => true do |t|
    t.string   "coordinates"
    t.integer  "x"
    t.integer  "y"
    t.integer  "page_id"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  add_index "coords", ["page_id"], :name => "index_coords_on_page_id"

  create_table "pages", :force => true do |t|
    t.string   "name"
    t.string   "description"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

end

Solution

  • Page

    class Page < ActiveRecord::Base
      has_many :coords
      has_many :comments, :through => :coords
    end
    

    Coord

    class Coord < ActiveRecord::Base
      belongs_to :page
      has_many :comments
    end
    

    Comment

    class Comment < ActiveRecord::Base
      belongs_to :coord
      has_one :page, :through => :coord
    end
    

    Using the above, you don't need page_id in the comments table.

    Reference: A Guide to Active Record Associations