Antonin Mrchd Antonin Mrchd - 5 days ago 6
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
end


And my post.rb file :

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

geocoded_by :country
after_validation :geocode
end


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

Answer

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

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

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

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