开发者

How to make the association work

开发者 https://www.devze.com 2023-03-14 03:04 出处:网络
I hav开发者_开发技巧e two models: class Group < ActiveRecord::Base belongs_to :sites end class Site < ActiveRecord::Base

I hav开发者_开发技巧e 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?


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消