Rails:获取用户访问"new"页面时的时间戳(并存入数据库)

Rails: Getting timestamp when user visits "new" page (and save it into the database)

我想在用户第一次访问 posts#new 页面 (.../posts/new) 时保存时间戳,并将此时间戳保存在 post s table 在数据库中。

到目前为止我做了什么

  1. 在 posts table 中,我添加并迁移了一个名为 first_time_visit 的列,其数据类型为 timestamp
  2. 在我的 posts_controller.rb 中,我初始化了一个 @post 并将 first_time_visit 属性设置为 Time.now
  3. 我已经将 "first_time_visit" 属性列入白名单。

问题:

在我的posts_controller.rb

def new 
  @post = Post.new(first_time_visit: Time.now)
end

def create
  @post = current_user.posts.build(post_params)

  if @post.save
    redirect_to posts_path, notice: "Post saved."
  else
    render 'new', notice: "Post could not be saved."
  end
end

...

private
def post_params
  params.require(:post).permit(:description, :link, :first_time_visit)
end 

我也尝试过另一种解决方案:

在我的 post.rb 模型中:

def add_first_time_visit(time)
  self.first_time_visit = time
end

在我的 posts_controller.rb:

def new 
  @post = Post.new
  @post.add_first_time_visit(Time.now)
end

但是这个解决方案也只给了我一个"nil"。

first_time_visit 作为隐藏字段添加到您的表单。

按照 Rails 的惯例,您应该在最后使用 at 命名您的日期时间字段。 first_time_visit => first_time_visited_at