我不明白爲什麼s.pages << page1
在Rails 4.1.1(我在rails控制檯中)中不起作用。 更多的背景,我的問題:我有一個subject.rb中和Page.rb爲模型,定義如下:Rails中的一對多關係 - MissingAttribute錯誤
class Subject < ActiveRecord::Base
has_many :pages
scope :visible, lambda { where (:visible => true) }
end
和
class Page < ActiveRecord::Base
belongs to :subject
end
在DB \遷移我有有2個遷移文件被執行:
class CreateSubjects < ActiveRecord::Migration
def up
create_table :subjects do |t|
t.string "name"
t.integer "position"
t.boolean "visible", :default => false
t.timestamps
end
end
def down
drop_table :subjects
end
end
而對於網頁:
class CreatePages < ActiveRecord::Migration
def up
create_table :pages do |t|
t.integer "subject_id"
t.string "name"
t.string "permalink"
t.integer "position"
t.boolean "visible", :default => false
t.timestamps
end
add_index("pages", "subject_id")
add_index("pages", "permalink")
end
def down
drop_table :pages
end
end
在rails控制檯中,我鍵入s = Subject.find_by_id(1),我得到預期的結果,來自具有id = 1的主題表的記錄然後,我鍵入:page1= Page.new(:name => "McCaine", :permalink => "first", :position => 1)
並創建了一條記錄,但沒有然後插入到數據庫中(因此此時它的頁面id = nil),因爲它首先需要與它所屬的主題鏈接。 因此,I型s.pages << page1
但我得到這個MissingAttribute錯誤:
←[1m←[35m (1.0ms)←[0m BEGIN ←[1m←[36mSQL (4.0ms)←[0m ←[1mINSERT INTO "pages" ("created_at", "name", "permalink", "position", "subject_id", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"←[0m [["create d_at", "2014-06-08 17:48:22.843764"], ["name", "McCaine"], ["permalink", "first"], ["position", 1], ["subject_id", 1], ["updated_at", "2014-06-08 17:48:22.843764"]] ←[1m←[35m (1.0ms)←[0m ROLLBACK ActiveModel::MissingAttributeError: can't write unknown attribute
page_id' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-4.1.1/lib/active_record/attribute_methods/write.rb:72:in
write_attribute' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-4.1.1/lib/active_record/attribute_methods/dirty.rb:68:inwrite_attribute' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-4.1.1/lib/active_record/attribute_methods.rb:390:in
[]=' ....
任何幫助嗎?
在此先感謝。
後來編輯:如圖所示由rake db:migrate:status
,頁面模型了:
Status Migration ID Migration Name
--------------------------------------------------
up 20140531184836 Create users
up 20140601105035 Alter users
up 20140601212417 Create subjects
up 20140601212440 Create pages
up 20140601212504 Create sections
就像一個調試目的..你能告訴我'rake db:migrate:status'的輸出嗎?這只是爲了測試「Page」模型的遷移是否已啓動或關閉。 –
感謝您回答Arup。頁面模型已啓動。我編輯了這個問題來表明這一點。 – Samy
好的。在控制檯上..只要輸入'Page'並告訴我你在看什麼? –