0

我有两个表,项目和类别。我已经预加载了 4 行的类别,每个项目必须属于 4 行之一。但是,当我尝试在命令行中添加现有项目和现有类别之间的关联时,我得到了这个:

> Project.find(11).category = Category.find(1)
Project Load (0.5ms)  SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1  [["id", 11]]
Category Load (0.7ms)  SELECT "categories".* FROM "categories" WHERE "categories"."id" = $1 LIMIT 1  [["id", 1]]
 => #<Category id: 1, name: "Photography", created_at: "2012-10-05 00:07:37", updated_at: "2012-10-05 00:07:37"> 
1.9.3p194 :004 > Project.find(11).category
Project Load (0.7ms)  SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1  [["id", 11]]
 => nil 
> Project.find(11).category
Project Load (0.4ms)  SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1  [["id", 11]]
 => nil 

很明显有些东西不起作用。我的迁移:

class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.string :filename
      t.string :location
      t.integer :id
      t.references :category
      t.timestamps
    end
  end
end

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.integer :id
      t.string :name, :default => "Design"
      t.timestamps
    end
  end
end

和型号:

class Category < ActiveRecord::Base
  attr_accessible :name, :id, :category_id
  has_many :projects 
    def to_hash
    {
      :id => self.id,
      :name => self.name
    }
  end
end

class Project < ActiveRecord::Base
  attr_accessible :id, :project_id, :filename, :location, :uploaded_file
  belongs_to :category
  def to_hash
    {
      :id => self.id,
      :filename => self.filename,
      :location => self.location
    }
  end
end

我哪里错了?提前感谢您阅读所有这些内容!

4

1 回答 1

3

你从来没有保存过记录。

project = Project.find(11)
project.category = Category.find(1)
project.save!
于 2012-10-05T00:57:10.893 回答