Don P
Don P

Reputation: 63748

Rails: ActiveRecord has_many association not working

I'm a bit new to Rails Active Record associations. I've tried to set up a relationship, but I get ActiveRecord error when I try to retrieve data. Did I associate my models incorrectly?

User has many Uploads, which has many UserGraphs:

class User < ActiveRecord::Base
  has_many :uploads, through: :user_graphs
end

class Upload < ActiveRecord::Base
  has_many :users, through: :user_graphs
end

class UserGraph < ActiveRecord::Base
  belongs_to :user
  belongs_to :upload
end

I want to get all of a user's uploads, and all of a user's graphs. The 2nd line doesn't work in rails console and gives an error

@user = User.find(1)
@uploads = @user.uploads

The error:

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :user_graphs in model User

Extra Credit:

If Users have Uploads that have UserGraphs... shouldn't it be has_many :uploads and has_many :user_graphs, through :uploads?

Upvotes: 3

Views: 2569

Answers (2)

John Feminella
John Feminella

Reputation: 311705

You didn't tell Rails that you have a user_graphs association on User, only an uploads association. So when Rails goes to follow the user_graphs association on uploads, it can't find it.

So, you need add the user_graphs association. Your models should look like this:

class User < ActiveRecord::Base
  has_many :user_graphs                       # <<< Add this!
  has_many :uploads, through: :user_graphs
end

class Upload < ActiveRecord::Base
  has_many :user_graphs                       # <<< Add this!
  has_many :users, through: :user_graphs
end

class UserGraph < ActiveRecord::Base
  belongs_to :user
  belongs_to :upload
end

Upvotes: 2

Tyler
Tyler

Reputation: 11499

Add

has_many :user_graphs

to the User and Upload classes.

The :through option defines a second association on top of this one.

Upvotes: 4

Related Questions