【问题标题】:Updating an ActiveAdmin nested resource using inputs not located on the table使用不在表上的输入更新 ActiveAdmin 嵌套资源
【发布时间】:2015-01-22 16:30:17
【问题描述】:

我目前在我的一个 activeadmin 页面中有一个嵌套资源的表单:

    f.inputs "Courses" do
      f.has_many :registrations, :allow_destroy => true, new_record: true do |tc|
        tc.input :course
        tc.input :semester
      end
    end

这是针对学生资源的。 学生通过注册拥有许多course_offerings。但是,我不希望用户直接从菜单中选择 course_offering(因为每年都会有很多重复相同的课程)。取而代之的是 coursesemester 的输入。 coursesemesterregistration 模型上的实例变量。它们在表单中设置,然后在保存后挂钩中找到正确的 course_offering,并与 registration 相关联。代码如下:

def semester=(s)
  @semester = s.to_i
end

def semester
  self.course_offering.semester
end

def course=(co)
  @course = co.to_i
end

def course
  self.course_offering.course
end

before_save :set_course_offering

def set_course_offering
  self.course_offering = CourseOffering.where(semester_id: @semester, course_id: @course).first
  #TODO: Handle case where no course offering is found
end

我有两个问题。第一个是当注册表为空时我得到一个零指针错误。

nil:NilClass 的未定义方法“课程”

我的 student 模型中有 Accept_nested_attributes 调用。

accepts_nested_attributes_for :registrations, :allow_destroy => true

这是我在查找错误时得到的唯一建议,但尽管有那段代码,但仍然得到它。当我删除 coursesemester 并将其替换为 course_offering 时,它似乎工作正常。

我遇到的下一个问题是学生记录在点击更新后没有保存。我认为这是因为当我只更新两个 coursesemester 实例变量时,我没有进行任何写入数据库的更改。我要么需要更新另一个输入,要么将调用添加到 term= 方法。

【问题讨论】:

    标签: ruby-on-rails ruby activeadmin


    【解决方案1】:

    您收到undefined method 错误,因为当注册表为空时,没有与您的学生相关联的课程设置,因此在课程的访问器方法中,您将获得nilself.course_offerings。你可以试试这个,它会考虑 nil 值:

    def course
      self.course_offering.try(:course)
    end
    

    您不需要accept_nested_attributes_for,因为您不想通过学生创建或修改课程设置。

    对于您的第二个问题:您对脏跟踪是正确的。您的模型未保存,因为您的学生模型尚未从 ActiveRecord 的角度进行修改。在保存模型之前,您需要使用course_attribute_will_change! 方法手动将属性(例如course_offering)标记为脏。

    虽然这种情况看起来像是引入表单对象的一个​​很好的例子。有一个很棒的库,叫做reform

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多