Ruby on rails 使用before_筛选器时,关联生成或创建时出现rails4错误

Ruby on rails 使用before_筛选器时,关联生成或创建时出现rails4错误,ruby-on-rails,activerecord,ruby-on-rails-4,Ruby On Rails,Activerecord,Ruby On Rails 4,我有这样的联想: has_many :exam_portions, -> { order :position } belongs_to :exam 在检查部分中,在保存回调之前有: before_create :proper_position private def proper_position self.position = exam.exam_portions.count end 尝试生成关联时,在保存回调之前引发以下错误: NoMethodError:nil:NilCl

我有这样的联想:

has_many :exam_portions, -> { order :position }
belongs_to :exam
在检查部分中,在保存回调之前有:

before_create :proper_position

private

def proper_position
  self.position = exam.exam_portions.count
end
尝试生成关联时,在保存回调之前引发以下错误:
NoMethodError:nil:NilClass的未定义方法“考试部分”

这是因为您的考试部分在创建过程中没有考试

如果以这种方式创建,它应该可以工作:

exam.exam_portions.create()
为了确保您的考试部分有一个考试,您应该在考试中添加验证

编辑

以下是我们对格奥尔基的了解:

exam = Gaku::Exam.where(:name => "Final", :use_weighting => true, :weight => 6).first_or_create 
# Does not work
exam_portion = exam.exam_portions.build(:name => 'Ruby 101', :max_score => 200).save
# Works
exam_portion = exam.exam_portions.create(:name => 'Ruby 101', :max_score => 200)

也许这是Rails 4中的一个bug。

这是因为您的考试部分在创建过程中没有考试

如果以这种方式创建,它应该可以工作:

exam.exam_portions.create()
为了确保您的考试部分有一个考试,您应该在考试中添加验证

编辑

以下是我们对格奥尔基的了解:

exam = Gaku::Exam.where(:name => "Final", :use_weighting => true, :weight => 6).first_or_create 
# Does not work
exam_portion = exam.exam_portions.build(:name => 'Ruby 101', :max_score => 200).save
# Works
exam_portion = exam.exam_portions.create(:name => 'Ruby 101', :max_score => 200)

也许这是Rails 4中的一个bug。

此代码在rails3中有效,但在rails4中无效。我尝试过创造和建造,但没有成功。同样的错误
exam=Gaku::exam.where(:name=>“Final”,:use_weighting=>true,:weight=>6)。first_或_create考试部分=考试。考试部分。build(:name=>'Ruby 101',:max_score=>200)。save
`你检查过考试记录是否被持久化了吗?是的,它被持久化了<代码>考试。持续?=>true有趣的是,当考试部分对象中的构建关联考试id为0时,这很有趣。但是你试过这样做吗?考试。考试部分。创建(:name=>'Ruby 101',:max\u score=>200)对感兴趣。创建工作和位置正确,然后保存回调工作。其中(:name=>'Ruby 101',:max_score=>200)。first_或_create没有。此代码在rails3上运行,但在rails4中没有。我尝试过创造和建造,但没有成功。同样的错误
exam=Gaku::exam.where(:name=>“Final”,:use_weighting=>true,:weight=>6)。first_或_create考试部分=考试。考试部分。build(:name=>'Ruby 101',:max_score=>200)。save
`你检查过考试记录是否被持久化了吗?是的,它被持久化了<代码>考试。持续?=>true有趣的是,当考试部分对象中的构建关联考试id为0时,这很有趣。但是你试过这样做吗?考试。考试部分。创建(:name=>'Ruby 101',:max\u score=>200)对感兴趣。创建工作和位置正确,然后保存回调工作。其中(:name=>Ruby 101',:max\u score=>200)。first\u或\u create没有。