开发者

Rails 2.3.8 Association Problem has_many belongs_to

I'm new to Rails. I have two models, Person and Day.

class Person < ActiveRecord::Base
  has_many :days
end

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

When I try to access @person.days I get an SQL error:

$ 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) 

I setup the association between the two before running any migrations, so I don't see why this has not been setup correctly.

Any suggestions?


Telling your model about the association doesn't set up the foreign key in the database - you need to create an explicit migration to add a foreign key to whichever table is appropriate.

For this I'd suggest:

script/generate migration add_person_id_to_days person_id:integer

then take a look at the migration file it creates for you to check it's ok, it should be something like this:

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

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

Run that and try the association again?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜