无法写出未知属性`challenge_id'

时间:2013-11-02 01:24:10

标签: ruby-on-rails ruby-on-rails-3 activerecord

我的代码是这样的:

的routes.rb

resources :challenges  do
   resources :problems
end

应用程序/模型/ challenge.rb

class Challenge < ActiveRecord::Base
  has_many :problems
end

应用程序/模型/ problem.rb

class Problem < ActiveRecord::Base
  belongs_to :challenge
end

分贝/迁移/ createchallenges.db

class CreateChallenges < ActiveRecord::Migration
  def change
    create_table :challenges do |t|
      t.string :name
      t.timestamps
    end
  end
end

分贝/迁移/ createproblems.rb

class CreateProblems < ActiveRecord::Migration
  def change
    create_table :problems do |t|
      t.belongs_to :challenge
      t.string :description
      t.timestamps
    end
  end

应用程序/控制器/ problem_controller.rb

class ProblemsController < ApplicationController
  def new
        @challenge = Challenge.find(params[:challenge_id])
        @problem = Problem.new(:challenge => @challenge)
  end
end

我可以创建一个没有问题的“挑战”,但是当我创建一个新的“问题”时,我收到了错误:

can't write unknown attribute `challenge_id'

@problem = Problem.new(:challenge => @challenge)

可能导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:1)

为具有belongs_to的模型创建db表时,请使用references

create_table :problems do |t|
  t.references :challenge
  t.string :description
  t.timestamps
end

您还可以通过查看db/schema.rb验证数据库是否已正确设置。

不要忘记进行迁移,简单但我偶尔会忘记。