开发者

Problem with associations in Rails

开发者 https://www.devze.com 2023-02-09 12:12 出处:网络
I\'ve been working on my Rails app and I am stuck with some associations that I can\'t get my head around.

I've been working on my Rails app and I am stuck with some associations that I can't get my head around.

Here are my models:

User Model

class User < ActiveRecord::Base
   has_many :events, :dependent => :destroy
end

Event Model

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :items, :dependent => :destroy
end

Item Model

class Item < ActiveRecord::Base
   belongs_to :event
end

When I head into the rails console and do something like this:

> User.last.events.last.items

I get an error like this:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no suc开发者_如何学Pythonh column: items.event_id: SELECT "items".* FROM "items" WHERE ("items".event_id = 1)

I have set my migrations like this:

class CreateItems < ActiveRecord::Migration
  def self.up
    create_table :items do |t|
      t.string :description
      t.string :name
      t.integer :event_id

      t.timestamps
    end
    add_index :items, :event_id
  end

  def self.down
    drop_table :items
  end
end

Is it something to do with my associations and the way that I have laid it out? Or is the the depth of the associations?

I hope that I've provided enough information.

Thanks everyone!


I'd suggest that you double check that you've run your migration (rake db:migrate).

It shouldn't matter, but you might also try "t.references :event" instead of "t.integer :event_id".

0

精彩评论

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