max pleaner
max pleaner

Reputation: 26758

failing to create Active Record Association

This is an extremely simple Active Record association I am trying to create and it is frustrating that is is not being made successfully.

I have two models, post and user. User.rb has nothing but has_many :posts and Post.rb has nothing but belongs_to :user. I have run rake db:migrate and verified that there is a user_id column in my posts table.

When I go to the console, though, I am unable to make an association between new objects.

First, I make a new User instance like max = User.create(:name=>"Max") Next, I make a new Post instance like post = Post.create(:user_id=>1, title=>"FirstPost")

I then try and type max.posts but get a NoMethodError undefined method 'post=' If I try and set up the association like max.post = post, I get the same error.

Lastly, I tried adding attr_accessor :posts to the User model.

Now, I can type max.posts, but I am just getting nil.

What am I missing here?

Upvotes: 1

Views: 115

Answers (1)

carpamon
carpamon

Reputation: 6623

That's because there's no 'post=' method in User.

Try the following:

max = User.create(:name=> "Max")
max.posts.create(:title => "FirstPost")
max.posts

As an alternative way:

max = User.create(:name=> "Max")
post = Post.new(:user => max, :title => "FirstPost")
post.save
max.posts

Upvotes: 1

Related Questions