2014-03-27 58 views
2

我覺得我在這裏忽略了一些明顯的東西。我可以創建故事模型和類別模型,但我無法將故事與類別關聯。has_one關係導致ActiveModel :: MissingAttributeError,我在這裏丟失了什麼?

這是我如何重現錯誤:

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

錯誤:::加載ActiveModel MissingAttributeError:不能寫未知屬性`story_id」

故事模式

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

故事遷移文件

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 

分類模型

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

類別遷移

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

回答

0

您在遷移錯過t.references :story。類別中的belongs_to方法需要story_id

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

你在你的Category模型缺少foreign_keystory_id。將該列添加到您的類別表中並遷移它。這將解決您的問題。

注意:在遷移更改之前,請回退以前的遷移。

OR

的最好方法是什麼@bekicot建議。只需添加t.references :story即可。這包括story_id,這樣它會默認添加到你的分類表中。

1

在您的故事模型中,將has_one :category更改爲belongs_to :category。一個經驗法則是如果你有一個模型的外鍵,你聲明關聯爲belongs_to。在此示例中,故事模型中有category_id,因此您在故事模型中使用belongs_to :category。這是非常有意義的,因爲故事應該屬於類別和類別has_many stories

+0

對我來說,困惑是,故事假設只有一個類別,而不是相反。 – bgreg

+0

是的,起初可能會讓人困惑,但你會習慣的。請記住,當你有'has_many'關係時,它的另一端的夥伴應該是'belongs_to'。一個類別has_many的故事,故事應屬於一個類別。 – jvnill

相關問題