简体   繁体   English

无法创建活动记录关联

[英]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. 这是我尝试创建的极其简单的Active Record关联,令人沮丧的是未成功创建。

I have two models, post and user. 我有两个模型,邮政和用户。 User.rb has nothing but has_many :posts and Post.rb has nothing but belongs_to :user . User.rb除了has_many :posts之外什么都没有,而Post.rb只有belongs_to :user什么都没有。 I have run rake db:migrate and verified that there is a user_id column in my posts table. 我已经运行rake db:migrate并验证了我的posts表中是否有一个user_id列。

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") 首先,我创建一个新的User实例,例如max = User.create(:name=>"Max")接下来,我创建一个新的Post实例,例如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. 然后,我尝试键入max.posts但得到一个NoMethodError undefined method 'post='如果我尝试建立类似于max.post = post的关联, max.post = post遇到相同的错误。

Lastly, I tried adding attr_accessor :posts to the User model. 最后,我尝试将attr_accessor :posts添加到User模型。

Now, I can type max.posts , but I am just getting nil . 现在,我可以输入max.posts ,但是我只是得到nil

What am I missing here? 我在这里想念什么?

That's because there's no 'post=' method in User. 那是因为User中没有'post ='方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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