ruby-on-rails - 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
解决方案
您可以在方法中填充该字段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
推荐阅读
- angular - 如何强制 Angular App 获取最新的 dist
- symfony - 在symfony 4中将树枝数据传递给vue js
- php - 循环遍历具有数组值的会话变量
- vue.js - 路由进入后未加载Vue Child
- r - 使用 R 通过 API 更新 Google Tag Manager 容器:invalidArgument 错误
- typescript - Visual Studio 代码禁用对象解构的代码格式
- jasper-reports - 如何将输入控件链接到报表的参数
- powerbi - Power BI - DAX 度量。来自另一个表的切片器值
- svg - 如何使垂直svg rect高度从底部开始?
- android - 带有生涩滚动的 RecyclerView