首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails,如何在模型中使用santize

Rails,如何在模型中使用santize
EN

Stack Overflow用户
提问于 2020-02-27 03:39:30
回答 1查看 28关注 0票数 0

我有以下型号

Diary.rb

代码语言:javascript
复制
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的正确语法是什么。

我的猜测,但这是失败的。

代码语言:javascript
复制
diary_year: subject_obj.diary_year

这是我的控制器

代码语言:javascript
复制
def create
    @diary = Diary.from_student(current_user, @student)
    @diary.save
    redirect_to @student, notice: "Diary was successfully created."
 end
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-27 05:21:52

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

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60421335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档