jeudi 8 décembre 2016

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

I want to save the timestamp when a user visits the posts#new page (.../posts/new) for the first time and save this timestamp in the posts table in the database.

What I've done so far

  1. In the posts table, I've added and migrated a column named first_time_visit which has the datatype timestamp
  2. In my posts_controller.rb I've initialised a @post with the first_time_visit attribute set to Time.now
  3. I have already whitelisted the "first_time_visit" attribute.

Problem:

  • After creating and saving a new post, the first_time_visit column is still "nil".

In my 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 

I've also tried another solution:

In my post.rb model:

def add_first_time_visit(time)
  self.first_time_visit = time
end

In my posts_controller.rb:

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

But this solution also only gives me a "nil".

Aucun commentaire:

Enregistrer un commentaire