在rails中的父验证中访问子模型

时间:2015-04-13 07:29:47

标签: ruby-on-rails

我有一个具有子模型的rails模型

class Student
  has_many :student_records, dependent: :destroy
  accepts_nested_attributes_for :student_records, :allow_destroy => true, reject_if: proc { |attributes| attributes['record'].blank? }

  # Now I would like to access the child model here during creating new records, for validation

  validate :sum_of_records_has_to_be_less_than_hundred

  def sum_of_records_has_to_be_less_than_hundred
    @sum = 0
    student_records.each do |sr|
      @sum += sr.record
    end
  end
  if @sum > 100
    errors.add(:base, :sum_of_records_has_to_be_less_than_hundred)
  end
end

class StudentRecord
  belongs_to :student
end

问题是student_records.each不起作用,因为student_records是空的,但我可以在params中看到它。发生了什么?

以下是学生控制器的一部分

Class StudentsController
  def new  
    @st = Student.new
    @st.student_records.build
  end

  def create
    @student = Studnet.new(student_params)
    if @student.save
      flash[:success] = t('student_saved')
      redirect_to students_url
    else
      render 'new'
    end
  end

  private
    def student_params
      params.require(:student).permit(:full_name, .......,
                                    student_records_attributes:
                                      [:id, :record, :_destroy])
    end
end

2 个答案:

答案 0 :(得分:0)

您错误地放置了验证方法之外的if...end。您也不必使用实例变量,局部变量将完成工作。

试试这个:

def sum_of_records_has_to_be_less_than_hundred
  sum = 0
  student_records.each do |sr|
    sum += sr.record
  end

  errors.add(:base, :sum_of_records_has_to_be_less_than_hundred) if sum > 100
end

答案 1 :(得分:0)

你能试试吗, 像这样更改您的验证来源:

def sum_of_records_has_to_be_less_than_hundred
    sum = 0
      self.student_records.each do |sr|
        sum += sr.record
      end 
   if sum > 100
     errors.add(:base, :sum_of_records_has_to_be_less_than_hundred)
   end
 end