has_one relationship is resulting in ActiveModel::MissingAttributeError , what am I missing here?

StackOverflow https://stackoverflow.com/questions/22681009

Вопрос

I feel like I am overlooking something obvious here. I can create a story model, and a category model, but I can't relate a story to a category.

Here is how I reproduce the error:

s = Story.new(title: "test", picture_url: "www.google.com") 
c = Category.last
s.category = c

error: ActiveModel::MissingAttributeError: can't write unknown attribute `story_id'

Story model

class Story < ActiveRecord::Base
 has_many :chapters, dependent: :destroy
 has_many :users, through: :story_roles
 has_one :category
end

Story migration file

class CreateStories < ActiveRecord::Migration
  def change
    create_table :stories do |t|
      t.string :title
      t.string :picture_url
      t.integer :category_id

      t.timestamps
    end
  end
end

Category model

class Category < ActiveRecord::Base
  belongs_to :story
  validates_presence_of :body
end

Category migration

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :body
      t.timestamps
    end
  end
end
Это было полезно?

Решение 2

You miss t.references :story in your migration. The belongs_to method on category requires story_id.

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.references :story
      t.string :body
      t.timestamps
    end
  end
end

Другие советы

In your story model, change has_one :category to belongs_to :category. A rule of thumb is if you have a foreign key for a model, you declare the association as belongs_to. In this example, you have category_id in the story model so you use belongs_to :category in the story model. This makes perfect sense since a story should really belong to a category and a category has_many stories.

You are missing a foreign_key story_id in your Category Model. Add that column in your categories table and migrate it.That would resolve your issue.

Note: Before migrating the changes,roll back the previous migration.

OR

The best way is what @bekicot suggested. Just add t.references :story. This includes story_id,so that it will be added to your categories table by default.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top