Martin
Martin

Reputation: 47

Two different results for "create" in Rails

I am trying to create a simple social network and therefore created the following UserFriendship class, which basically has a user and friend (also a user).

When I call UserFriendship.request(users(:user1), users(:user2)) it should add two friendships to the database (user1, user2) and (user2, user1).

However, instead of adding to complete datasets to the database. Friendship1 is incomplete. I dont' understand why create works in friendship2 but not in friendship1.

Here friendship1 & friendship2 after they are created:

<UserFriendship id: nil, user_id: 755095536, friend_id: 204282540, created_at: nil, updated_at: nil, state: "pending">

<UserFriendship id: 980190966, user_id: 204282540, friend_id: 755095536, created_at: "2013-12-08 20:04:51", updated_at: "2013-12-08 20:04:51", state: "requested">

The UserFriendship id:, created_at: and updated_at: is nil in Friendship1 but not in Friendship2

class UserFriendship < ActiveRecord::Base
    belongs_to :user
    belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'

    scope :accepted, -> { where(state: 'accepted') }
    scope :pending,  -> { where(state: 'pending') }

    validates :friend_id, uniqueness: { scope: :user_id }

    after_destroy :destroy_mutual_friendship!

    state_machine :state, :initial => :pending do
            after_transition on: :accept, do: [:send_acceptance_email, :update_mutual_friendship!]
            state :requested

            event :accept do
            transition any => :accepted
            end
    end

    def self.request(user1, user2)
            transaction do
            friendship1 = create(user: user1, friend: user2, state: 'pending')
            friendship2 = create(user: user2, friend: user1, state: 'requested')

            friendship1.send_request_email unless friendship1.new_record?
            friendship1
            end
    end
...
end

Upvotes: 0

Views: 51

Answers (2)

Peter Alfvin
Peter Alfvin

Reputation: 29399

friendship1 is not being saved, which means it has probably failed the one validation you have, namely that a friendship between these two users doesn't already exist.

Upvotes: 1

janfoeh
janfoeh

Reputation: 10328

Use create! instead of create within your transaction. The bang variant throws an exception on failure, causing the transaction to rollback and giving you a better idea on what fails.

Upvotes: 1

Related Questions