简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM