プロジェクトとカテゴリの 2 つのテーブルがあります。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
どこが間違っていますか?このすべてを読んでくれてありがとう!