Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top