Rails关联无法正常工作

时间:2012-10-05 00:53:19

标签: ruby-on-rails

我有两个表,项目和类别。我预先加载了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

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

1 个答案:

答案 0 :(得分:3)

你从未保存过记录。

project = Project.find(11)
project.category = Category.find(1)
project.save!