user984621
user984621

Reputation: 48453

Rails 3 - model issue, foreign key

I have two models, Like and Photo.

class Like < ActiveRecord::Base
  belongs_to :photo, :class_name => "DataLike", :foreign_key => "photo_id"
end

class Photo < ActiveRecord::Base  
  has_many :likes
end

And now I try to execute this query:

query = Like.select(:photo_id).joins(:photo).count

But I am still getting this error:

uninitialized constant Like::DataLike

Could anyone help me, please, what I am doing wrong?

Thank you so much

Upvotes: 1

Views: 577

Answers (1)

Benoit Garret
Benoit Garret

Reputation: 13675

You don't seem to have a DataLike model, my best guess is that you want to link to the Photo model:

class Like < ActiveRecord::Base
  belongs_to :photo, :foreign_key => "photo_id"
end

class Photo < ActiveRecord::Base  
  has_many :likes
end

If you leave out the :class_name option, the Photo model is inferred. It's used to specify the class of the linked model, in case it is different from the association name.

Upvotes: 3

Related Questions