ironsand
ironsand

Reputation: 15141

How to save another column updated time?

I have a Post model that have a read_status boolean column. I want to add a read_at column that saves timestamp of when read_status is updated.

How can I hook the event read_status is updated?

Currently I'm updating read_statsu by user click with these codes:

read_statsu.js

$(function(){
    $('.edit_company').submitOnCheck();
});

posts.js

jQuery.fn.submitOnCheck = function () {
    this.find('input[type=submit]').remove();
    this.find('input[type=checkbox]').click(function () {
    $(this).parent('form').submit();
    });  
    return this;
};

posts_helper.rb

  def read_checkbox(post)
    if user_signed_in?
      form_for(post, remote: true) do |f|
        str = f.check_box :read
        str += f.submit
        str
      end
    end
  end

Maybe I had better create a another model for read status?

Upvotes: 1

Views: 88

Answers (3)

Divya Shrestha
Divya Shrestha

Reputation: 433

First you need to create a migration to add the read_at column to your posts table.

 rails g migration AddReadAtToPosts read_at: timestamps

Then add the following to your Posts model

before_save :updated_read_at
private
def updated_read_at
  self.read_at = Time.zone.now if featured_changed?
end

Upvotes: 2

Joel
Joel

Reputation: 4593

I would create a sub model of your Post model. Lets call it PostRecord.

So your Post model will have a has_many relationship with PostRecord, and PostRecord will belong to Post

class Post < ActiveRecord::Base
  has_many :post_records
end

class PostRecord < ActiveRecord::Base
   belongs_to :post
end

Your PostRecord model will have:

post_id as type integer 
read_at as type string

In your Post model you should define a method like this:

def updated_read_at
 self.post_record.create post_id: self.id, read_at: Time.now if read_status_changed?
end

More information on the changed? method

Upvotes: 3

Darkmouse
Darkmouse

Reputation: 1939

First you need to create a migration to add the read_at column to your posts table.

rails g migration AddReadAtToPosts read_at: timestamps

Then add the following to your Posts Controller

def show
  @post = Post.find(params[:id])
  @post.update_attribute(:read_at => Time.now)

If a user clicks on a post, that posts' 'read_at' attribute will be updated with the current time.

Upvotes: 1

Related Questions