ruby-on-rails - Rails mongodb - 在字段 :date 中设置今天的日期

标签 ruby-on-rails mongoid

我想为我的 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/

相关文章:

ruby-on-rails - 我如何添加将在 rake test :db:prepare in Rails 之后运行的任务

ruby-on-rails - 使用 Sidekiq 运行更复杂的作业

ruby-on-rails - 可以生成支架将 Controller 放在命名空间中吗?

jquery - rails : Saving an ordered list with empty values

ruby-on-rails - Rspec 测试以检查创建对象的值

ruby-on-rails - Mongoid 中 ActiveRecord#establish_connection 的等价物是什么?

ruby-on-rails - 在 force_ssl 之前重定向到 'www'

ruby-on-rails - Rails 5.2.3 至 6.0.0 升级

ruby-on-rails - Mongoid:返回 embedded_in 类

ruby-on-rails - 将项目插入mongoid数组