2010-08-29 116 views
2

我是Rails的新手。我有兩個模型,人和日。Rails 2.3.8關聯問題has_many belongs_to

class Person < ActiveRecord::Base 
    has_many :days 
end 

class Day < ActiveRecord::Base 
    belongs_to :person 
    has_many :runs 
end 

當我嘗試訪問@ person.days我得到一個SQL錯誤:

$ script/consoleLoading development environment (Rails 2.3.8) 
ree-1.8.7-2010.02 > @person = Person.first 
=> #<Person id: 1, first_name: "John", last_name: "Smith", created_at: "2010-08-29 14:05:50", updated_at: "2010-08-29 14:05:50"> ree-1.8.7-2010.02 
> @person.days 
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: days.person_id: SELECT * FROM "days" WHERE ("days".person_id = 1) 

我安裝運行任何遷移前兩者之間的關聯,所以我不明白爲什麼這有沒有正確設置。

有什麼建議嗎?

回答

3

告訴你關於關聯的模型不會在數據庫中設置外鍵 - 你需要創建一個明確的遷移來將外鍵添加到適合的表中。

爲此,我會建議:

腳本/生成遷移add_person_id_to_days PERSON_ID:整數

然後看看它會創建遷移文件爲你檢查它的確定,應該是這樣的:

class AddPersonIdToDays < ActiveRecord::Migration 
    def self.up 
    add_column :days, :person_id, :integer 
    end 

    def self.down 
    remove_column :days, :person_id 
    end 
end 

運行並再次嘗試關聯?