2016-11-27 65 views
1

我在这里问这个问题,因为我没有找到任何解决我的问题的答案。我想创建一个职位belongs_to旅行,所以每个旅行都有很多职位。但是,当我创建的帖子我有我的看法此错误消息:钢轨错误类必须存在 - 关联

1错误禁止本文从beign保存 旅游必须存在

因此,这里是我的travel.rb文件:

class Travel < ApplicationRecord 
    has_many :posts 
    belongs_to :user 
end 

而且我post.rb文件:

class Post < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :travel 

    geocoded_by :country 
    after_validation :geocode 
end 

是否有人知道问题出在哪里,并可以解释我的解决方案? 非常感谢!

回答

5

导轨5使得默认情况下需要关联belongs_to。所以,你不能没有它用Travel

@post = Post.new(post_params) 
@post.travel = travel 
@post.save 

关联创建Post如果你想建立关联可选的,你必须明确地提到它

class Post < ActiveRecord::Base 
    belongs_to :travel, optional: true 
end 
+0

嗨!谢谢你的答案,但我没有Post.create在我的posts_controller.rb中,我使用这个方法:@post = Post.new(posts_params),我在新方法中传递了这些参数:(:title,:country ,:description) –

+3

对,不过你要创建后期对象,在保存之前必须确保它与旅行对象相关联 – usha

+1

@AntoninMrchd'@post = Post.new(params); @ post.save'(基本上)是'Post.create(params)'的更长版本。 – guiniveretoo