Only one side of join table is being saved

In my app, User objects can follow each other, and be followed. The two
relationships are distinct.

I’m seeing that when I set user_a.follows << user_b that
user_b.followed_by.count still == 0. Why?

When I play in the console, I see:

$ jordan = User.new(:name=>"Jordan")
 => #<User id: nil, name: "Jordan">
$ matt = User.new(:name=>"Matt")
 => #<User id: nil, name: "Matt">
$ matt.followers << jordan
 => [#<User id: nil, name: "Jordan">]
$ matt.followers.first
 => #<User id: nil, name: "Jordan">
$ jordan.friends.first
 => nil
$ matt.save

 SQL (14.1ms)  INSERT INTO "users" ("name") VALUES (?)  [["name",
"Matt"]]
  SQL (0.3ms)  INSERT INTO "users" ("name") VALUES (?)  [["name",
"Jordan"]]
  SQL (0.4ms)  INSERT INTO "followings" ("followee_id", "follower_id")
VALUES (?, ?)  [["followee_id", nil], ["follower_id", 2]]
 => true

My objects are defined as:

class User < ActiveRecord::Base
  has_many  :follower_followee_rel,
            :class_name         => "Following",
            :foreign_key        => 'followee_id',
            :dependent          => :destroy
  has_many  :friends,
            :through            => :follower_followee_rel,
            :source             => :followee
  has_many  :followee_follower_rel,
            :class_name         => 'Following',
            :foreign_key        => 'follower_id',
            :dependent          => :destroy
  has_many  :followers,
            :through            => :followee_follower_rel,
            :source             => :follower
end

class Following < ActiveRecord::Base
  belongs_to  :followee,
              :class_name         => 'User'
  belongs_to  :follower,
              :class_name         => 'User'
end

Totally ignoring the second half of the relationship.

No errors are raised. What’s going on?

On 18 September 2011 19:26, Jordan F. [email protected] wrote:

In my app, User objects can follow each other, and be followed. The two
relationships are distinct.

I’m seeing that when I set user_a.follows << user_b that
user_b.followed_by.count still == 0. Why?

I have not looked at your code in detail (no time at the moment) but
have you tried reloading user_b from the db again? Possibly the one
you have in memory will not know about the extra connection.

Colin

$ matt.followers.first
VALUES (?, ?) [[“followee_id”, nil], [“follower_id”, 2]]
:foreign_key => ‘followee_id’,
:source => :follower
Totally ignoring the second half of the relationship.
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.


gplus.to/clanlaw

This is a total left field possibility, but I recently encountered a
MySQl bug in a join query and found that upgrading fixed it. Here are
my very verbose details: