2016-11-27 62 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