O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.3. Defining Associations

That doesn't look too good, now, does it? The problem lies in the fact that the app\views\comments\new.html.erb template that's generated by scaffold expects Comment model objects to have an article method. This is not automatically the case because you have not specified an association between the Article and Comment models. To do that, edit the Article model to include the following highlighted line:

class Article < ActiveRecord::Base
  has_many :comments

  # ... other existing code ...
end

Similarly, the Comment model, located in app\models\comment.rb, should look like the following:

class Comment < ActiveRecord::Base
  belongs_to :article
end

Starting with Rails 2.2 belongs_to is automatically populated for you when scaffolding. In earlier versions it had to be manually specified.

The highlighted lines employ methods to define associations between models that in turn represent relationships between the respective tables in the database. In this case, you defined a one-to-many relationship between Article and Comment.

As you can see, the syntax of these associated methods is very straightforward. Each of them receives a symbol that indicates the associated object (plus optional arguments). They end up reading like common speech: an article "has many comments" and a comment "belongs to an article."

Notice how the symbol passed to the has_many method is plural, whereas the argument for belongs_to is singular. Other association methods are has_one (for one-to-one ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required