Ruby on rails Active Record和Rails-帮助配置正确的关联
我正在寻找一些非常简单的东西,我过去做过,但我停止了编码几个月,几乎忘记了一切:( 我有一个多对多的协会 -一个机构提供多种服务 -一项服务由几个机构提供 我的模型 Agency.rbRuby on rails Active Record和Rails-帮助配置正确的关联,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我正在寻找一些非常简单的东西,我过去做过,但我停止了编码几个月,几乎忘记了一切:( 我有一个多对多的协会 -一个机构提供多种服务 -一项服务由几个机构提供 我的模型 Agency.rb class Agency < ActiveRecord::Base has_many :agency_services has_many :services, through: :agency_services end 在Rails控制台中 seo.agencies 返回一个提供“seo”服务的
class Agency < ActiveRecord::Base
has_many :agency_services
has_many :services, through: :agency_services
end
在Rails控制台中
seo.agencies
返回一个提供“seo”服务的代理的数组,这很好(这里是“a”代理)
但是,当我试图反向搜索并找到“a”机构提供的所有服务时,我找不到它
a.services
返回
#<ActiveRecord::Associations::CollectionProxy []>
返回代理提供的服务的数组
及
返回
#<ActiveRecord::Associations::CollectionProxy []>
#
我不明白…正如我所看到的,您的型号
代理服务
有外键代理id
。它应该是代理id
a = Agency.new(name:"A Agency", description:"Best agency")
a.save
seo = Service.new(name:"Seo", description:"Improve Google result")
seo.save
agency_service = AgencyService.new(agency_id:1, service_id:1)
agency_service.save
seo.agencies
a.services
我希望这将对您有所帮助这是它的设置方式:
#app/models/agency.rb
class Agency < ActiveRecord::Base
has_many :agency_services
has_many :services, through: :agency_services
end
#app/models/agency_service.rb
class AgencyService < ActiveRecord::Base
belongs_to :agency
belongs_to :service
end
#app/models/service.rb
class Service < ActiveRecord::Base
has_many :agency_services
has_many :agencies, through: :services
end
--
考虑到您的表格设置如下,这应该是可行的:
谢谢您的回答。不幸的是,即使使用正确的外键,它也不起作用。
a.id
和agency\u服务的结果是什么。agency\u id
?两者都返回“1”但现在它工作了,a.services和seo.agencies。非常奇怪,但问题解决了,非常感谢您的帮助!!哦,代理服务不需要这样做,非常感谢!我会做得更好。
a.services
seo.agencies
#<ActiveRecord::Associations::CollectionProxy []>
a = Agency.new(name:"A Agency", description:"Best agency")
a.save
seo = Service.new(name:"Seo", description:"Improve Google result")
seo.save
agency_service = AgencyService.new(agency_id:1, service_id:1)
agency_service.save
seo.agencies
a.services
#app/models/agency.rb
class Agency < ActiveRecord::Base
has_many :agency_services
has_many :services, through: :agency_services
end
#app/models/agency_service.rb
class AgencyService < ActiveRecord::Base
belongs_to :agency
belongs_to :service
end
#app/models/service.rb
class Service < ActiveRecord::Base
has_many :agency_services
has_many :agencies, through: :services
end
a = Agency.new(name:"A Agency", description:"Best agency")
a.save
seo = agency.services.new(name:"Seo", description:"Improve Google result")
seo.save
#agency_service should be populated automatically