Has_many :through problems -- please help


#1

I’m having a lot of trouble with has_many, :through and could really
use some assistance.

I’ve got a User and Group class. Users can subscribe to groups, and
groups should know who’s subscribed.

I’ve got a join table (group_subscriptions) with group_id, user_id,
and it’s own id element.

Users has “has_many :groups, :through => :group_subscription” and
Groups has “has_many :users, :through => :group_subscription”. I
also have a group_subscription.rb model that has “belongs_to :user
newline belongs_to :group”

I just wanted to test out working with this kind of functionality, so
I’ve got this simple code:

@user = User.find(1)
@group = Group.find(1)
@user.groups << @group
@user.save

but I get the error
“ActiveRecord::HasManyThroughAssociationNotFoundError”. I’m running
Webrick on OS X, have restarted it, and have looked everywhere to no
avail in this problem.

Michael J.
removed_email_address@domain.invalid


#2

I haven’t tested this out but I suspect that this should work. This is
what I have and it works fine.

User.rb
has_many :group_subscription
has_many :groups, :through => :group_subscription

Group.rb
has_many :group_subscription
has_many :users, :through => :group_subscription

-Eric

Michael J. wrote:

Groups has “has_many :users, :through => :group_subscription”. I also



Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails


Eric G.
http://www.ericgoodwin.com


#3

Oops,
Forgot the plural.

User.rb
has_many :group_subscriptions
has_many :groups, :through => :group_subscriptions

Group.rb
has_many :group_subscriptions
has_many :users, :through => :group_subscriptions

-Eric

Eric G. wrote:

and it’s own id element.
@group = Group.find(1)


Eric G.
http://www.ericgoodwin.com


#4

Yep, I tried both plural and non-plural forms. Rails didn’t like
either.

Michael J.
removed_email_address@domain.invalid


#5

No dice, that didn’t seem to work :-\

Michael J.
removed_email_address@domain.invalid


#6

Michael J. wrote:

Yep, I tried both plural and non-plural forms. Rails didn’t like
either.

Michael J.
removed_email_address@domain.invalid

You also need to have a class for the join model. In
group_subcription.rb:

class GroupSubscription < AR::Base
belongs_to :user
belongs_to :group
end

I have some examples on my blog.


Josh S.
http://blog.hasmanythrough.com