ceth
ceth

Reputation: 45285

How to make the association work

I have two models:

class Group < ActiveRecord::Base
  belongs_to :sites
end

class Site < ActiveRecord::Base
  has_many :groups
end

I can get all groups which belongs to site:

Site.find(1).groups

But I can not get site to which belongs given group:

$ Group.find(1)
#<Group id:1 ...., site_id: "1">
$ Group.find(1).sites
nil

Why?

Upvotes: 1

Views: 54

Answers (2)

brad
brad

Reputation: 9773

If it doesn't work you can always just add the following public method to group.rb

def site
  Site.find self.site_id
end

Upvotes: -1

Atzoya
Atzoya

Reputation: 1387

Probably because the group belongs to 1 it should be in singular form

$ Group.find(1).site

And also as Marcel Jackwerth said the belongs_to should also be in singular form

class Group < ActiveRecord::Base
  belongs_to :site
end

Upvotes: 2

Related Questions