trowse trowse - 25 days ago 10
Ruby Question

Track Dates of viewed article

I am working through my first Ruby on Rails App!

I have followed along with ruby's getting started tutorial and created a blog. http://guides.rubyonrails.org/getting_started.html

I am trying to implement a way to track when articles are viewed so I created a second table/model/controller that I'd like to insert the current date every time an article is viewed (show).

I'm not really sure how to implement this though... my initial though was in the article controller under the show def I would do something like


@view = View.new(view_params)
@view.Save!


This didn't really work. Any idea at all?

Thanks

Answer

You didn't mention what columns you had in your new model, but I'm assuming it's just the default timestamps and a field for the article ID.

So, within the 'show' action for the articles, you could do something like this. Your action names and such may differ, but the principle is the same.

def show
  @article = Article.find(params[:id])
  View.create(article_id:@article.id)
end

I can't think of any reason why you'd need to store the view itself in an instance variable, or any variable for that matter.

Comments