首页 > 解决方案 > Rails , 如何在模型中消毒

问题描述

我有以下型号

日记.rb

class Diary < ApplicationRecord
    belongs_to :student
    belongs_to :user
    belongs_to :grade
    has_many :diary_entries

    validates :diary_year, presence: true

    def self.from_student(owner, student_obj)
        new(
            user_id: owner.id,
            student_id: student_obj.id,
            grade_id: student_obj.grade_id,
 #How to add diary_year here..... 
        )
    end
      
end

我的日记只有三个属性,user_id、grade_id、student_id...我添加了一个额外的属性 diary_year,diary_year 是一个整数,我不确定将它添加到 self.from_student 的正确语法是什么。

我的猜测,但这失败了。

diary_year: subject_obj.diary_year

这是我的控制器

def create
    @diary = Diary.from_student(current_user, @student)
    @diary.save
    redirect_to @student, notice: "Diary was successfully created."
 end

标签: ruby-on-rails

解决方案


您可以在方法中填充该字段Date.today.year

class Diary < ApplicationRecord
    belongs_to :student
    belongs_to :user
    belongs_to :grade
    has_many :diary_entries

    validates :diary_year, presence: true

    def self.from_student(owner, student_obj)
        new(
        user_id: owner.id,
        student_id: student_obj.id,
        grade_id: student_obj.grade_id,
        diary_year: Date.today.year #this populates the field automatically
        )
    end

end

推荐阅读