I’m looking for something very easy, I did it in the past but I stoped coding for several months and I forgot almost everything 🙁
I have a many to many association
– One agency provide several services
– One service is provided by several agencies
My models
Agency.rb
class Agency < ActiveRecord::Base
has_many :agency_services
has_many :services, through: :agency_services
end
Service.rb
class Service < ActiveRecord::Base
has_many :agency_services
has_many :agencies, through: :agency_services
end
Agency_service.rb
class AgencyService < ActiveRecord::Base
belongs_to :service
belongs_to :agency
end
Then, I have a seeds.rb where I create the data in my database
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
In the Rails Console
seo.agencies
Return an array with the agency providing the “seo” service, which is nice (here the “a” agency)
But, when I try to reverse the search and find all the services provided by the “a” agency, I can’t find it
a.services
Return
#<ActiveRecord::Associations::CollectionProxy []>
In my mind, by doing a.services I should have an array of all the services provided by agency_id:1 (the “a” agency), so in this case the “Seo” service.
Do you see what I’m doing wrong ?
Thank you 🙂
Edit : It’s strange because now the
a.services
Return the array of the service provided by the agency
And
seo.agencies
Return
#<ActiveRecord::Associations::CollectionProxy []>
I don’t understand …
2
Answers
As I can see, your model
AgencyService
have foreign keyagence_id
. It should beagency_id
I hope this would help you
This is how it should be set up:
This will allow you to use the following seeds:
—
This should work, considering you have the tables set up as below: