在我的应用程序中,如果在创建记录时它是空的,我想在字段中添加一个值。它应该取文件的名称(附在记录上。
我尝试将下面的代码添加到控制器,但是没有这样做。如何/应该在Rails 5中完成这些操作?
def create
@document = Document.new(document_params)
if @document.update(document_params)
unless @document.name.present?
@document.name == @document.file_file_name
end
redirect_to @document
else
render 'new'
end
end
答案 0 :(得分:1)
使用self.attribute
向模型before_save :set_field_name
添加回调并添加了一个方法:
def set_field_name
unless self.name.present?
self.name = self.file_file_name
end
end