【问题标题】:rails4 error on association build or create when using before_filter使用 before_filter 时关联构建或创建时出现 rails4 错误
【发布时间】:2013-06-03 12:52:52
【问题描述】:

我有这个关联:

has_many :exam_portions, -> { order :position }
belongs_to :exam

exam_portion 中有 before_save 回调:

before_create :proper_position

private

def proper_position
  self.position = exam.exam_portions.count
end

当尝试建立关联时, before_save 回调会引发以下错误: NoMethodError: undefined method 'exam_portions' for nil:NilClass

【问题讨论】:

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


    【解决方案1】:

    这是因为您的考试部分在创建期间没有考试。

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

    exam.exam_portions.create()
    

    为确保您的考试部分有考试,您应该在考试中添加 validate_presence。

    编辑

    这是我们对 Georgi 的发现:

    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 中的一个错误。

    【讨论】:

    • 这段代码在 rails3 上运行,但在 rails4 上不行。我尝试创建和构建没有成功。同样的错误。 exam = Gaku::Exam.where(:name => "Final", :use_weighting => true, :weight => 6).first_or_create exam_portion = exam.exam_portions.build(:name => 'Ruby 101', :max_score => 200).save`
    • 您是否检查过考试记录是否已保留?
    • 是的,它是持久的。 exam.persisted? => true 有趣的是,在exam_portion 对象中建立关联exam_id 时为0
    • 这很有趣。但是您是否尝试过这样做? Exam.exam_portions.create(:name => 'Ruby 101', :max_score => 200)
    • 有趣的 .create 工作和位置是正确的,并且 before_save 回调工作。与 where(:name => 'Ruby 101', :max_score => 200).first_or_create 没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多