cjm2671
cjm2671

Reputation: 19456

Simple ActiveRecord Association problem

I am learning Rails, so this is a very simple problem.

I am trying to associate Users<-Posts in the classic one-to-many style- user's own posts.

Here are my models:

class Post < ActiveRecord::Base
  attr_accessible :body
  belongs_to :user  
end

class User < ActiveRecord::Base
  has_many :posts
  attr_accessible :email, :password, :password_confirmation
end

I also created the necessary migration:

class AddUserIdToPosts < ActiveRecord::Migration
  def self.up
    add_column :posts, :user_id, :integer
  end

  def self.down
    remove_column :posts, :user_id
  end
end

The problem I'm facing is trying to get rails to see all of this and correctly build the association.

When I call:

@user = User.first
@user.post.build

I get a

NoMethodError: undefined method `post' for #<User:0x10319fbc8>

What have I missed?

Upvotes: 0

Views: 132

Answers (4)

Bohdan
Bohdan

Reputation: 8408

it should be user.posts but post.user

Upvotes: 2

Jawad Rashid
Jawad Rashid

Reputation: 36

You have declared the association is User model as has_many :posts so the association will be available to you by using @user.posts.build instead of @user.post.build.

Upvotes: 2

apneadiving
apneadiving

Reputation: 115511

You have a has_many relationship so:

@user.posts.build

Upvotes: 1

pcg79
pcg79

Reputation: 1283

If a user has_many Posts the correct call is:

@user.posts.build

Notice the plural posts.

Upvotes: 2

Related Questions