Antonin Mrchd Antonin Mrchd - 1 year ago 197
Ruby Question

rails error Class must exist - Associations

I ask this question here because I don't find any answer that resolve my problem. I want to create a post belong_to travel, so each travel have many post. But when I create the Post I have on my view this error message :

1 error Prohibited this article from beign save
Travel must exist

So here is my travel.rb file :

class Travel < ApplicationRecord
has_many :posts
belongs_to :user

And my post.rb file :

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

geocoded_by :country
after_validation :geocode

Does someone know where is the problem and could explain me a solution ?
Thank a lot !

Answer Source

Rails 5 makes belongs_to association required by default. So you cannot create Post without associating it with a Travel

@post = = travel

If you want to make the association optional, you will have to mention it explicitly

class Post < ActiveRecord::Base
   belongs_to :travel, optional: true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download