Eugenio Herrera
Eugenio Herrera

Reputation: 137

ActiveModel::UnknownAttributeError in rails 5

I'm trying to make a reddit-like website, so I've created a Forum model which should contain posts, hence I also created a Post model which I want to be a Forum child. My code for this idea is:

forum.rb

class Forum < ApplicationRecord
  has_many :posts

  validates :name, presence: true,
                length: { minimum: 2 }
end

post.rb

class Post < ApplicationRecord
  validates :title, presence: true,
                length: { minimum: 5 }
  validates :text, presence: true,
                length: { minimum: 5 }
  belongs_to :forum
end

The corresponding migrations are:

create_forums.rb

class CreateForums < ActiveRecord::Migration[5.1]
  def change
    create_table :forums do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end

create_posts.rb

class CreatePosts < ActiveRecord::Migration[5.1]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :text
      t.references :forum, index: true, foreign_key: true

      t.timestamps
    end
  end
end

My problem arise when I try to create a new post given a certain forum. For example, if I run @forum.posts.create(title: "Title", text: "Body") I get ActiveModel::UnknownAttributeError in Posts#new with the description unknown attribute 'forum_id' for Post.

What is going on?

Upvotes: 0

Views: 1813

Answers (2)

Ishan Patel
Ishan Patel

Reputation: 6091

Have you migrated your db? If no, then rails db:migrate

and then reset your db: rails db:setup

That should fix the issue.

Upvotes: 0

Wakeuphate
Wakeuphate

Reputation: 503

Have you run your migrations after generating them? ( rake db:migrate )

The only way I can get this error to occur in testing is to remove the forum reference/relationship field from the posts table and then try and create a post related to the forum. When the migration is run with the t.references :forum, index: true, foreign_key: true the command runs perfectly for me.

If you added the reference line after running the migration, you could reset your database by running rake db:drop db:create db:migrate and you should be good to go since you have it in the table creation migration file, but it is worth noting that if you want to add or remove columns or modify your database, you should be creating new migrations for this instead of running through the drop/create process.

Upvotes: 1

Related Questions