我覺得我在這裏忽略了一些明顯的東西。我可以創建故事模型和類別模型,但我無法將故事與類別關聯。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
對我來說,困惑是,故事假設只有一個類別,而不是相反。 – bgreg
是的,起初可能會讓人困惑,但你會習慣的。請記住,當你有'has_many'關係時,它的另一端的夥伴應該是'belongs_to'。一個類別has_many的故事,故事應屬於一個類別。 – jvnill