Rails:在用户访问时获取时间戳" new"页面(并将其保存到数据库中)

时间:2016-12-08 14:36:30

标签: ruby-on-rails ruby-on-rails-3 timestamp

我希望在用户第一次访问帖子#new page(... / posts / new)时保存时间戳,并将此时间戳保存在数据库的posts表中。

到目前为止我做了什么

  1. 在posts表中,我添加并迁移了名为first_time_visit的列,该列具有数据类型timestamp
  2. 在我的posts_controller.rb中我初始化了一个@post,其first_time_visit属性设置为Time.now
  3. 我已经将" first_time_visit"属性。
  4. 问题:

    • 创建并保存新帖子后,first_time_visit列仍然是" nil"。

    在我的posts_controller.rb

    java.util.concurrent

    我还尝试了其他解决方案:

    在我的post.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 
    

    在我的posts_controller.rb中:

    def add_first_time_visit(time)
      self.first_time_visit = time
    end
    

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

1 个答案:

答案 0 :(得分:1)

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

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