使用create方法创建N-M关系未知属性错误

时间:2013-12-02 18:48:51

标签: ruby-on-rails

以下是我的迁移:

class CreateTests < ActiveRecord::Migration
  def change
    create_table :tests do |t|
      t.string :value

      t.timestamps
    end
  end
end

class CreateQuestions < ActiveRecord::Migration
  def change
    create_table :questions do |t|
      t.string :title

      t.timestamps
    end
  end
end

class CreateQuestionsTests < ActiveRecord::Migration
  def change
    create_table :questions_tests do |t|
      t.integer :test_id
      t.integer :question_id

      t.timestamps
    end
  end
end

现在在rails控制台中我创建了一个测试对象和一个问题对象

test = Test.create(value: "10")
question = Question.create(title: "blablabla")

如果我现在test.questions.create(question_id: question.id)我收到以下错误:

ActiveRecord::UnknownAttributeError: unknown attribute: question_id

怎么样?

2 个答案:

答案 0 :(得分:0)

如果你使用has_and_belongs_to_many关系,你必须要有没有id和邮票的关系表

class CreateQuestionsTests < ActiveRecord::Migration
  def change
    create_table :questions_tests, :id => false do |t|
      t.integer :test_id
      t.integer :question_id
    end
  end
end

答案 1 :(得分:0)

我想你想在这里做一个Rich关联,如果是这样你应该在你的模型中声明这样的关系:

Test.rb

class Test < ActiveRecord::Base
    has_many :questions_tests
    has_many :questions, :through => :questions_tests # here you tell rails that your Test model has many questions if you go through questions_tests
end

Question.rb

 class Question < ActiveRecord::Base
     has_many :questions_tests
     has_many :tests, :through => :questions_tests # here you tell rails that your Question model has many tests if you go through questions_tests
 end

QuestionTest.rb

class QuestionTest < ActiveRecord::Base
    belongs_to :test
    belongs_to :question
end

这样你就可以直接遍历关联表(questions_tests):test.questions.create(question_id: question.id),你也有这种可能性:

test = Test.create(value: "10")
question = Question.create(title: "blablabla")
test.questions_tests << question # or question.questions_tests << test