帮助我理解为什么这些ActiveRecord模型会抛出异常

时间:2011-03-16 10:50:12

标签: ruby-on-rails activerecord

这些是我的模型(两者都只有name:string属性):

class Category < ActiveRecord::Base
    has_many :subcategories
end

class Subcategory < ActiveRecord::Base
    belongs_to :category
end

我开始了rails console

> c = Category.new(:name => "C1")
=> #<Category id:nil, name:"C1", created_at:nil, updated_at: nil>
> c.save
=> true
> s = c.subcategories.create(:name => "S1")
=> #<Subcategory id:2 name:"S1", created_at: "2011-03-16 17:45:18", updated_at: "2011-03-16 17:45:18">
> s.category
=> nil
> s.save
=> true
> c.subcategories
=> ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column subcategories.category_id: SELECT "subcategories".* FROM "subcategories" WHERE("subcategories".category_id = 2)

为什么s.category为零?为什么我收到SQLException?我的模特有问题吗?我要参加一对多的协会。

2 个答案:

答案 0 :(得分:2)

看起来您的子类别表缺少category_id列,它需要将记录与类别相关联。创建一个迁移以添加它:

# Rails 3
rails g migration AddCategoryIdToSubcategories category_id:integer

# Rails 2
script/generate migration AddCategoryIdToSubcategories category_id:integer

然后运行您的迁移,它应该可以正常工作。

答案 1 :(得分:-1)

是的......它会产生问题,因为c.subcategories总是返回一个数组(可能是空白的) 你可以这样试试。

 c = Category.new(:name => "C1")
 s = Subcategory.new(:name => "S1")
 c.subcategories = [s]
 c.save

希望它能奏效。