Bitwise
Bitwise

Reputation: 8461

Custom updated_at for a specific field/attribute in rails

I currently have a method that increments an attribute on the Subscriber. It's visit attribute that takes in a int. My question is - Can I find that Subscriber that last had their visit attribute updated? In the console it would look something like this - Subscriber.find("visit +=1").last <- completely wrong BTW, but I assume it would look kinda like that? Does anybody know how I can call this in the console?? Any help would be great.

Controller Method:

def visit
  @subscriber = Subscriber.find_by(params[:phone_number])
  if @subscriber
    @subscriber.visit ||= 0
    @subscriber.visit += 1
    @subscriber.save
    flash[:notice] = flash[:notice] = "Thank You #{@subscriber.first_name}. You have #{@subscriber.days_till_expired} until renewal"
    redirect_to subscribers_search_path(:subscriber)
  else
    render "search"
  end
end 

As you can see I would like to call the Subscriber who last used this method to update the visit attribute on their object. Let me know if you need more info.

Upvotes: 2

Views: 616

Answers (1)

Kumar
Kumar

Reputation: 3126

You can always get the last updated item like this:

Subscriber.order('updated_at desc').first

But :updated_at will update even if anything other than :visit is updated. So you have to write a little migration to add a custom field which will do the work for us.

rails g migration AddLastVistedToSubscriber last_visited:datetime

Run rake db:migrate to add :last_visited to our table. Now we need to update that field whenever we're doing +1 to :visit.

def visit
  @subscriber = Subscriber.find_by(params[:phone_number])
  if @subscriber
    @subscriber.visit ||= 0
    @subscriber.visit += 1
    if @subscriber.save
      @subscriber.touch(:last_visited) #this will update the last_visited with the update time
      flash[:notice] = flash[:notice] = "Thank You #{@subscriber.first_name}. You have #{@subscriber.days_till_expired} until renewal"
      redirect_to subscribers_search_path(:subscriber)
    end
  else
    render "search"
  end
end

Now we can search easily which subscriber's :visit was incremented last.

Subscriber.order('last_visited desc').first

Upvotes: 3

Related Questions