Niels
Niels

Reputation: 609

Ruby on Rails: associations

I'm pretty new to ROR so I'm stuck at the moment with this problem.

I'm setting up an application with articles and templates. I want to create templates with many articles, and the same articles can be assigned to several different templates. So when you create a templates I want to assign articles to it. You will think directly use a has_many association but I don't think this grasps my problem.

I want to assign articles to multiple templates so I thought using a linking table of some sort would be at place here.

But I don't know how to do it in rails! Or what kind of solution I should look for.

Is there anybody who could advise me with this problem ?

Upvotes: 0

Views: 102

Answers (3)

Suborx
Suborx

Reputation: 3669

You can create linking model articles_template

rails generate model articles_template

with references to article and template

class CreateArticlesTemplates < ActiveRecord::Migration
  def change
    create_table :articles_templates do |t|
      t.references :article
      t.references :template
      t.timestamps
    end
  end
end

and then set the association in model articles_template

class ArticlesTemplate < ActiveRecord::Base
  belongs_to :article
  belongs_to :template
end

class Article < ActiveRecord::Base
  has_many :articles_templates
  has_many :templates, :through => :articles_templates
end

class Template < ActiveRecord::Base 
  has_many :articles_templates
  has_many :articles, :through => articles_templates
end

IMHO this is the best practice because you can add some extra functionality right into the linking model and table. (more about this here)

Upvotes: 2

J. Martin
J. Martin

Reputation: 1737

Try checking out stuff on has_and_belongs_to_many

Essentially, go to the console and type

$ rails g model article title:string body:text

$ rails g model template name:string some_other_attributes:type etc etc

$ rails g migration create_articles_templates

Then edit the create_articles_templates with:

class CreateArticlesTemplates < ActiveRecord::Migration
  def up
    create_table :articles_templates, :id => false do |t|
      t.integer :template_id, :article_id
    end
  end

  def down
  end
end

Upvotes: 1

Flexoid
Flexoid

Reputation: 4245

Are you looking for has_and_belongs_to_many association?

http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association

Upvotes: 1

Related Questions