How to achieve has many through relation between users - ruby-on-rails

I am building matching system between users, originally it was has and belongs to many association, but due to some validations and additional data i need for that join table, i need to have model for that one, and change it to has many through.
has_and_belongs_to_many(:likes,
class_name: :User,
join_table: :user_likes,
foreign_key: :user_liker_id,
association_foreign_key: :user_liked_id)
has_and_belongs_to_many(:likeds,
class_name: :User,
join_table: :user_likes,
foreign_key: :user_liked_id,
association_foreign_key: :user_liker_id)
This is old implementation which needs to be converted to has_many through. As you can see, with this one i can retrieve all users which i liked and users which liked me. I have created UserLike model but i don't have any success with making it workable inside user model. What i already tried is following:
user.rb
has_many :user_likes
has_many :likes, through: :user_likes, foreign_key: :user_liked_id
has_many :likeds, through: :user_likes, foreign_key: :user_liker_id
user_like.rb
class UserLike < ApplicationRecord
belongs_to :user
end
This implementation raises following exception:
ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) "like" or :likes in model UserLike. Try 'has_many :likes, :through => :user_likes, :source => '. Is it one of user or user_likes?
I don't know what i am missing here, any help would be appreciated :)

When creating a join table that joins the same table twice you need two separate associations since the user can be in either foreign key:
class User < ApplicationRecord
has_many :likes_as_liker,
class_name: 'Like',
foreign_key: 'liker_id'
has_many :likes_as_liked,
class_name: 'Like',
foreign_key: 'liked_id'
end
class Like < ApplicationRecord
belongs_to :liker, class_name: 'User'
belongs_to :liked, class_name: 'User'
end
With our two has_many associations done we can start creating indirect associations:
class User < ApplicationRecord
has_many :likes_as_liker,
class_name: 'Like',
foreign_key: 'liker_id'
has_many :likes_as_liked,
class_name: 'Like',
foreign_key: 'liked_id'
has_many :likers,
through: :likes_as_liked
has_many :liked_users,
through: :likes_as_liker,
source: :liked
end
Which works perfectly:
irb(main):002:0> u.likers
User Load (2.8ms) SELECT "users".* FROM "users" INNER JOIN "likes" ON "users"."id" = "likes"."liker_id" WHERE "likes"."liked_id" = $1 LIMIT $2 [["liked_id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy []>
irb(main):003:0> u.liked_users
User Load (1.3ms) SELECT "users".* FROM "users" INNER JOIN "likes" ON "users"."id" = "likes"."liked_id" WHERE "likes"."liker_id" = $1 LIMIT $2 [["liker_id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy []>

As per the description mentioned in the post you are trying to find the users which have liked my post and the users whom I have liked.
Below mentioned code does not tell rails that likes and likeds are actually users.
has_many :user_likes
has_many :likes, through: :user_likes, foreign_key: :user_liked_id
has_many :likeds, through: :user_likes, foreign_key: :user_liker_id
Modify it to below
has_many :user_likes
has_many :likes, through: :user_likes, foreign_key: :user_liked_id, source: :liked
has_many :likeds, through: :user_likes, foreign_key: :user_liker_id, source: :liked
Best Approach is specifying class along with class name so that rails know in which class is mapped to this foreign key when specifying customized relation names
When your association name is different than the name used at the :through you have to define the source parameter. If you look at the exception message it explicitly asks you to do it.
Hope it answers the question.

Related

Joining Nested Associations (Multiple Level)

I have the following models and relationships:
A User has many Offers (where he/she is the seller), an Offer has many Purchases, a Purchase has many Accbooks
Models and associations:
class User < ApplicationRecord
has_many :offers, foreign_key: :seller_id
has_many :purchases, foreign_key: :buyer_id
end
class Offer < ApplicationRecord
has_many :purchases
belongs_to :seller, class_name: 'User'
end
class Purchase < ApplicationRecord
belongs_to :offer
belongs_to :buyer, class_name: 'User'
has_one :seller, through: :offer
has_many :accbooks, class_name: 'Admin::Accbook', foreign_key: 'purchase_id'
end
module Admin
class Accbook < ApplicationRecord
belongs_to :purchase
end
end
I want to get all the Accbooks of any given user (as a seller). The equivalent SQL statement would look like this:
SELECT "accbooks".*
FROM "accbooks"
INNER JOIN "purchases" ON "purchases"."id" = "accbooks"."purchase_id"
INNER JOIN "offers" ON "offers"."id" = "purchases"."offer_id"
INNER JOIN "users" ON "users"."id" = "offers"."seller_id"
WHERE "users"."id" = ?
So far I've tried this:
Admin::Accbook.joins( {purchase: :offer} )
Which gives me this SQL as a result:
SELECT "accbooks".*
FROM "accbooks"
INNER JOIN "purchases" ON "purchases"."id" = "accbooks"."purchase_id"
INNER JOIN "offers" ON "offers"."id" = "purchases"."offer_id"
Now I don´t know how to add the join to the User model, and then how to add the Where condition.
Thanks for any insight.
You can joins the relations together and apply where clause on the joined relations:
Admin::Accbook
.joins(purchase: :offer)
.where(offers: { seller_id: 123 })
A thing to know, where uses the DB table's name. joins (and includes, eager_load, etc) uses the relation name. This is why we have:
Admin::Accbook
.joins(purchase: :offer)
# ^^^^^ relation name
.where(offers: { seller_id: 123 })
# ^^^^^^ table name
Try Adding following association in users.rb
has_many :accbooks, through: :purchases
So your problem is user is acting as 2 roles for same accounts. You can try something like below stuff
class User < ApplicationRecord
has_many :offers, foreign_key: :seller_id
has_many :purchases, foreign_key: :buyer_id
has_many :offers_purchases,
through: :offers,
:class_name => 'Purchase',
:foreign_key => 'offer_id',
:source => :purchases
end

Rails self join with has_many through relationship

Users can follow other Users through FollowingRelationship
I would like to be able to say
User.first.followings and it returns a list of Users
This is not working:
Class User
has_many :following_relationships
has_many :followings, through: :following_relationships, foreign_key: :following_id, source: :user
end
Class FollowingRelationship
attr_accessible :following_id, :follower_id
belongs_to :followings, class_name: "User"
end
User.first.followings gives this in console:
SELECT "users".* FROM "users" INNER JOIN "following_relationships" ON "users"."id" = "following_relationships"."user_id" WHERE "following_relationships"."user_id" = 1
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: following_relationships.user_id: SELECT "users".* FROM "users" INNER JOIN "following_relationships" ON "users"."id" = "following_relationships"."user_id" WHERE "following_relationships"."user_id" = 1
Anyone see what piece I am missing?
I think the problem is that FollowingRelationship model doesn't have any relation with User.
It should have belongs_to :user since you specify source: :user, shouldn't it?
I don't quite understand your models and relations between them but belongs_to :followings looks rather strange.
belongs_to uses singular form since it can't belong to more than one object.
UPDATE 1
To be more clear.
I think you should have
class FollowingRelationship
…
belongs_to :user
belongs_to :follower
end
That means followings_relationships table should have user_id and follower_id columns.
UPDATE 2
After some conversation we have figured it out.
Here is the code you should have
class User < ActiveRecord::Base
has_many :fade_relationships, foreign_key: :faded_id
has_many :fadings, through: :fade_relationships, source: :fading
end
class FadeRelationship < ActiveRecord::Base
attr_accessible :faded_id, :fading_id
belongs_to :fading, class_name: "User"
end

setting up association for a has_one that is self-referential

I have a User and a Reviewer table.
Reviewer tracks user_id and reviewer_id
now my association is setup like this:
# reviewer
has_one :reviewer
accepts_nested_attributes_for :reviewer
has_many :active_managements, class_name: 'Reviewer',
foreign_key: 'reviewer_id',
dependent: :destroy
has_one :my_reviewer, through: :reviewer, source: :user
what I'm trying to set up is that a User can have one reviewer, but can review many.
Now I'm trying to make it so that I can do
current_user.my_reviewer.first_name
f.ex and get the first name of the reviewer of the current user. However currently the
has_one :my_reviewer, through: :reviewer, source: :user
just goes to yourself. Which I think has to do with the source. If I try to change it to :reviewer I get this error:
Could not find the source association(s) :reviewer in model Reviewer. Try 'has_many :my_reviewer, :through => :reviewer, :source => <name>'. Is it one of user or reviewer_user?
and if I change it to reviewer_user
I get this error:
PG::UndefinedColumn: ERROR: column reviewers.reviewer_user_id does not exist
LINE 1: ... "users" INNER JOIN "reviewers" ON "users"."id" = "reviewers...
^
: SELECT "users".* FROM "users" INNER JOIN "reviewers" ON "users"."id" = "reviewers"."reviewer_user_id" WHERE "reviewers"."user_id" = $1 LIMIT 1
Reviewers are Users, right? So why not just get rid of the reviewer table and do this:
# user
has_many :reviewees, class_name: "User", foreign_key: "my_reviewer_id"
belongs_to :my_reviewer, class_name: "User"

Has many :through a Polymorphic association not aliasing type column with Squeel 1.1.1

I've got a few classes:
class Membership < ActiveRecord::Base
belongs_to :group
belongs_to :member, polymorphic: true
end
class User < ActiveRecord::Base
has_many :memberships, as: :member, dependent: :destroy
has_many :groups, through: :memberships
end
class Package < ActiveRecord::Base
has_many :memberships, as: :member, dependent: :destroy
has_many :groups, through: :memberships
end
and
class Group < ActiveRecord::Base
has_many :memberships, dependent: :destroy, inverse_of: :member
has_many :packages, through: :memberships, source: :member, source_type: 'Package'
has_many :users, through: :memberships, source: :member, source_type: 'User'
end
A Users and Packages can have membership in a Group. All of this appears to be ok until I try to get the Users that belong to a Group. In the console, with an instance of a Group g:
[5] pry(main)> g.users
User Load (3.3ms) SELECT "USERS".* FROM "USERS" INNER JOIN "MEMBERSHIPS" ON
"USERS"."ID" = "MEMBERSHIPS"."MEMBER_ID" WHERE "MEMBERSHIPS"."GROUP_ID" = :a1 AND
"USERS"."MEMBER_TYPE" = 'User' [["group_id", 10000]]
OCIError: ORA-00904: "USERS"."MEMBER_TYPE": invalid identifier:
SELECT "USERS".*
FROM "USERS"
INNER JOIN "MEMBERSHIPS" ON "USERS"."ID" = "MEMBERSHIPS"."MEMBER_ID"
WHERE "MEMBERSHIPS"."GROUP_ID" = :a1
AND "USERS"."MEMBER_TYPE" = 'User'
It's easy to see the error - the Users table doesn't have the Member_Type column, it resides on the Membership table.
Why is the column not being aliased appropriately? Anyone else having this problem?
Update
This is an issue with Squeel - removing it from my Gemfile and the association behaves properly.
Logged an issue - https://github.com/ernie/squeel/issues/288

has_many of itself through something

So, I have a system where users are able to follow authors (other users).
User Model:
class User < ActiveRecord::Base
has_many :author_following, class_name: 'Following'
has_many :following, through: :author_following, source: :author
has_many :followers, foreign_key: 'author_id', through: :author_following, source: :user
end
Following Model:
class Following < ActiveRecord::Base
belongs_to :user
belongs_to :author, foreign_key: 'author_id', class_name: "User"
end
Issue: I am able to get the list of authors that i am following, but I am able to get the list of my followers.
Given: u is a valid user that is following others and has followers
u.following generates the following SQL:
SELECT "users".* FROM "users" INNER JOIN "followings" ON "users"."id" = "followings"."author_id" WHERE "followings"."user_id" = $1 [["user_id", 1]]
Which is correct..
u.followers generates the following SQL:
SELECT "users".* FROM "users" INNER JOIN "followings" ON "users"."id" = "followings"."user_id" WHERE "followings"."user_id" = $1 [["user_id", 1]]
Which is wrong..
Ideally this SQL would be WHERE "followings"."author_id" = $1
Of course, I figure it your right after posting the question. However if you think there is a more elegant way of doing this, please comment :)
To solve, I changed:
User Model:
class User < ActiveRecord::Base
has_many :author_following, class_name: 'Following'
has_many :following, through: :author_following, source: :author
has_many :author_followers, foreign_key: 'author_id', class_name: 'Following'
has_many :followers, through: :author_followers, source: :user
end
Following Model:
class Following < ActiveRecord::Base
belongs_to :user
belongs_to :author, class_name: "User"
end
Another way is to use has_and_belongs_to_many. No second model needed.
class User < ActiveRecord::Base
has_and_belongs_to_many :followers, class_name: 'User', foreign_key: 'follower_id'
has_and_belongs_to_many :followees, class_name: 'User', foreign_key: 'followee_id'
end
# Migration
create_table :followees_followers do |t|
t.belongs_to :followee
t.belongs_to :follower
end
This is simpler, but the validation part(say verifying somebody is an author) need to be done in User model
#Billy Chan's answer above is close, but you also need to specify the other side of relationship as well with "association_foreign_key", and switch follower_id with followee_id on our side. Also, join table is users_users actually.
class User < ActiveRecord::Base
has_and_belongs_to_many :followers, class_name: 'User',
foreign_key: 'followee_id', association_foreign_key: 'follower_id'
has_and_belongs_to_many :followees, class_name: 'User',
foreign_key: 'follower_id', association_foreign_key: 'followee_id'
end
# Migration
create_table :users_users do |t|
t.belongs_to :followee
t.belongs_to :follower
end
Now User.followers and User.followees work as expected

Resources