Search code examples
ruby-on-railsrubyhas-manymodel-associationsbelongs-to

how to associate two models using has_many and belongs_to ruby on rails


I have generated two models tour and tourcategories in my application. Now I want to associate these two models using has_many and belongs_to. Where tour can relate with single tourcategory but tourcategory can have more than one tours. So definition of the tour model is following:

class Tour < ActiveRecord::Base
  belongs_to :tourcategory
  attr_accessible :content, :element_id, :job_id, :title, :priority, :tourcategory
end

this is the definition of tourcategory model:

class Tourcategory < ActiveRecord::Base
  has_many :tours
  attr_accessible :title
end

this is the definition of the tours migration file: class CreateTours < ActiveRecord::Migration

def change
    create_table :tours do |t|
      t.string :element_id
      t.string :title
      t.text :content
      t.integer :job_id
      t.integer :priority
      t.belongs_to :tourcategory, index:true
      t.timestamps
    end
  end
end

this is the definition of the tours controller :

def new
        @tourcategories = Tourcategory.all
        @tour = Tour.new
        @tour.build_tour
        respond_to do |format|
        format.html
        format.json { render json: @tour }
        end
    end

Now I am getting an error

undefined method `tourcategories'

When I access the _form.html.haml view for editing and for adding new tour. this the code where error is encountered.

.field
    = label_tag "tour Categories"
    %br/
    = select_tag "tourcategory", options_from_collection_for_select(Tourcategory.all, 'id', 'title', @tour.tourcategories.map{ |j| j.id })
    = f.submit

Solution

  • You actually need to use HABTM (Has And Belongs To Many) - please check out Rails documentation for more details