我想为我的 Controller 的 :date 字段自动添加今天的日期。 我是 Rails 的新手,不知道如何设置此默认值,除非它必须在 Controller 中。
这是我的 Post 模型:
class Post
include Mongoid::Document
field :title, type: String
field :text, type: String
field :date, :type => DateTime
end
还有我的 Post Controller :
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
private
def post_params
params.require(:post).permit(:title, :text, :date)
end
在 Rails 文档中,我读到了 Date.current 或 Date.today。
最佳答案
你总是可以让 Mongoid 为你处理默认值
class Post
include Mongoid::Document
field :title, type: String
field :text, type: String
field :date, :type => DateTime, default: ->{ Date.today }
end
这样,如果您的参数中的日期为零,它将被设置为今天的日期。
记录了默认值 here.
关于ruby-on-rails - Rails mongodb - 在字段 :date 中设置今天的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22050408/