PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

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

 October 21, 2022     belongs-to, has-many, model-associations, ruby, ruby-on-rails     No comments   

Issue

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



Answered By - SpeedyWizard
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing