Benjamin Crouzier
Benjamin Crouzier

Reputation: 41945

Customizing amistad : adding timestamps

I am using the gem amistad to manage friendships in my application.

I would like to track when relationships occur to be able to display some notifications.

First, I would like to add a timestamp to the relationship model in order to be able to do queries such as : retrieve all Friendships where receiving user is current user, and where updated_at is greater than the last time the current_user checked his notifications. By counting those results I can say: 3 incoming contact requests and display them.

So I made a migration:

class AddUpdatedAtToFriendship < ActiveRecord::Migration
  def change
    change_table :friendships do |t|
      t.timestamps
    end
  end
end

rake db:migratemigrates correctly, but then the updated_at is not automatically when records are created or updated via the gem (eg: @user.invite another_user).

FYI, the invite method is the following: (code here)

def invite(user)
      return false if user == self || find_any_friendship_with(user)
      Amistad.friendship_class.new{ |f| f.friendable = self ; f.friend = user }.save
end

I don't see why the active record auto timestamps doesn't work in this case.

Note: If I manually create a friendship in the console, the timestamps are set:

$> rails c
test = Amistad::Friendships::UserFriendship.new
test.friend_id = 1
test.friendable_id = 2
test.save
test.updated_at
=> Thu, 23 May 2013 17:59:17 CEST +02:00

Even If I do that in the console timestamps are set : So it must be a context problem...

$> rails c
test2 = Amistad.friendship_class.new{ |f| f.friendable = User.find_by_id(5) ; f.friend = User.find_by_id(6) }.save
test2.updated_at
=> Thu, 23 May 2013 18:02:05 CEST +02:00

But still, when I call @user.invite another_user in the application, it doesn't update the timestamps...


Second, in the rails console, if I type Friendships.all, Friendship.all, Amistad::Friendships.all... I get :

NameError: uninitialized constant Friendship


How can I solve those 2 problems. Any suggestions ?

Upvotes: 0

Views: 275

Answers (1)

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41945

To access the Friendship model, use: Amistad::Friendships::UserFriendship.all

The migration is fine. There is nothing else to do in order to have the fields automatically updated.

Don't forget to restart the server so that Active Record picks up the changes of the migration !

Upvotes: 0

Related Questions