0

I have a model favorit_group (user:references, group:references).

And would like to find all the favorites groups of my User with something like that :

current_user.fav_groups

I suppose that i have to write something like this in my model User, but it's not working

has_many :favorit_groups, dependent: :destroy
has_many :fav_groups, through: :favorit_groups, class_name: "Group"

Is anyone who is working with this kind of association ? Or should I have to join and merge the model favorit_groups inside my User model ?

stig Garet
  • 564
  • 2
  • 13
  • 1
    Take a look at the `source` option: https://stackoverflow.com/questions/4632408/understanding-source-option-of-has-one-has-many-through-of-rails – MrYoshiji Oct 31 '17 at 14:01

2 Answers2

2

As the relation name fav_groups is not the same as the relation name between FavoritGroup and Group, Rails does not not how to fetch those records.

Luckily, has_many accept a source option:

has_many :fav_groups, source: :group, through: :favorit_groups, class_name: "Group"

See full explanation here: https://stackoverflow.com/questions/tagged/ruby-on-rails

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • My mistake, I did'nt edit my question but I have also try with 'group' – stig Garet Oct 31 '17 at 13:53
  • Could not find the source association(s) "fav_group" or :fav_groups in model FavoritGroup – stig Garet Oct 31 '17 at 13:54
  • I'm already using the user.groups association, and I would like to buid something similar for the favorites groups – stig Garet Oct 31 '17 at 13:55
  • 1
    Are you sure you are not calling fav_group/fav_groups somewhere else on a FavoritGroup object by mistake? This part you described us seems correct – Ursus Oct 31 '17 at 13:56
  • I don't think so, So if I understand you well, something like : has_many :favorit_groups, dependent: :destroy has_many :fav_groups, through: :favorit_groups, class_name: "Group" Should be correct ? – stig Garet Oct 31 '17 at 13:58
  • You are missing the `source: :group` option (https://stackoverflow.com/questions/4632408/understanding-source-option-of-has-one-has-many-through-of-rails) – MrYoshiji Oct 31 '17 at 14:00
  • After the class name ? – stig Garet Oct 31 '17 at 14:01
0

Its look like there is many to many relationship between user and group

class User

  has_many :favorit_groups, dependent: :destroy
  has_many :fav_groups, through: :favorit_groups, source: :group

end

Try current_user.groups which will automatical fire a join query and fetch those groups that are marked favorite by the use i.e those groups for which an entry is present in favorit_groups table

Nimish Gupta
  • 3,095
  • 1
  • 12
  • 20
  • 2
    Thanks for your answer but I need the association current_user.groups for other stuff, so I would like to build a new one with a scope .fav_groups – stig Garet Oct 31 '17 at 13:53