0

i have a "Question" model and a "Tag" model. I added a many-to-many association to these two model. that's what i have now :

class Question < ActiveRecord::Base
  attr_accessible :content, :score, :title
   has_and_belongs_to_many :tags

end

class Tag < ActiveRecord::Base
  attr_accessible :description, :name
   has_and_belongs_to_many :questions
end

What should i do to update the database and the controllers ?

thanks

user3242743
  • 1,751
  • 5
  • 22
  • 32
  • check if this helpfull http://stackoverflow.com/questions/5120703/creating-a-many-to-many-relationship-in-rails-3 – Rahul Singh Feb 01 '14 at 13:22

2 Answers2

0

You can consult with Rails Guide on associations here. Here's a code snippet right from there:

# Models
class Assembly < ActiveRecord::Base
  has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies
end

# Corresponding migration for creating models and join table
class CreateAssembliesAndParts < ActiveRecord::Migration
  def change
    create_table :assemblies do |t|
      t.string :name
      t.timestamps
    end

    create_table :parts do |t|
      t.string :part_number
      t.timestamps
    end

    create_table :assemblies_parts do |t|
      t.belongs_to :assembly
      t.belongs_to :part
    end
  end
end
marvelousNinja
  • 1,510
  • 9
  • 15
0

Create a migration for the join table with the following command:

$ rails g migration questions_tags question_id:integer tag_id:integer

Create the table in the database:

$ rake db:migrate

Rails magic will help you populate the join table. I created a many-to-many code quiz with a has_and_belongs_to_many example that you might find helpful.

Powers
  • 18,150
  • 10
  • 103
  • 108