Nathan
Nathan

Reputation: 3185

Trouble setting up ActiveRecord many to many relationship

I'm having some difficulty in getting a many to many relationship working in my Rails app. I'm running Ruby 2.2.2p95 and Rails 4.2.0.

NoMethodError: undefined method `each' for #<Topic id: 1>
seeds.rb:63:in `<top (required)>'

My video model:

class Video < ActiveRecord::Base
    has_and_belongs_to_many :topic
end

The topic model:

class Topic < ActiveRecord::Base
    has_and_belongs_to_many :video
end

The join table migration:

class TopicsVideos < ActiveRecord::Migration
  def up
    create_table :topics_videos, id: false do |t|
      t.belongs_to :topic_id, index: true
      t.belongs_to :video_id, index: true
    end
  end
  def down
    drop_table :topics_videos
  end
end

The error is happening in the db seeder:

62 | @topicTest= Topic.create!(title: 'Test')
63 | Video.create!(title: 'Test', topic: @topicTest)

I'm still really new to Rails, coming from PHP, and this one is stumping me at the moment. Any help would be greatly appreciated.

Upvotes: 0

Views: 54

Answers (2)

Nitish Parkar
Nitish Parkar

Reputation: 2868

First of all has_and_belongs_to_many association names should be plural.

Video model:

class Video < ActiveRecord::Base
    has_and_belongs_to_many :topics
end

Topic model:

class Topic < ActiveRecord::Base
    has_and_belongs_to_many :videos
end

Then you can use create method added by has_and_belongs_to_many

@topicTest= Topic.create!(title: 'Test')
@topicTest.videos.create!(title: 'Test')

Or

@topicTest= Topic.create!(title: 'Test')
@topicNew= Topic.create!(title: 'New')

video = Video.create!(title: 'Test')
@topicTest.videos << video
@topicNew.videos << video

For more details, refer to HABTM section in Rails Guides

Upvotes: 1

Alex Pan
Alex Pan

Reputation: 4581

You need to pluralize the relationship model like so:

The video model:

class Video < ActiveRecord::Base
    has_and_belongs_to_many :topics
end

The topic model:

class Topic < ActiveRecord::Base
    has_and_belongs_to_many :videos
end

Upvotes: 1

Related Questions