我有以下型号
Diary.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发布于 2020-02-27 05:21:52
您可以在方法中使用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
endhttps://stackoverflow.com/questions/60421335
复制相似问题