0

I am a beginner in rails, and I have a question about accessing one model from another model that is associated with several degrees of separation.

Let's say I have these models:

Account has_many Spies
Spy has many SpyRelationships and belongs to Account
SpyRelationship belongs to Listing and belongs to Spy

How would I set up the associations so that I could simply pull all the listings associated with a given Account (via its spies and spyrelationships)? What line of code would allow me to do so, after those associations are setup properly?

Isaac Y
  • 660
  • 1
  • 9
  • 27

1 Answers1

1

I'm guessing you want to access a listing through a spy?

class Account < ActiveRecord::Base
  has_many :spies
  has_many :listings, through: :spies
end

class Spy < ActiveRecord::Base
  belongs_to :account
  has_many   :spy_relationships
  has_many   :listings, through: :spy_relationships
end

class SpyRelationship < ActiveRecord::Base
  belongs_to :listing
  belongs_to :spy
end

class Listing < ActiveRecord::Base
  has_many :spy_relationships
end
Trip
  • 26,756
  • 46
  • 158
  • 277
  • Thank you for this. Actually I am trying to access listings through the account....is that possible? – Isaac Y May 28 '14 at 17:05
  • Great, thank you. Currently in my listing controller I have the following query....how could I adjust it so that it only pulls the Listings for the current_user ? @listings = Listing.search(params[:query], page: params[:page]) – Isaac Y May 28 '14 at 19:44
  • @IsaacYerushalmi This sounds like an unrelated question. You should probably mark this question as done, and post a new question and be sure to show your model arrangement for `current_user` and how it relates to `Listing` – Trip May 28 '14 at 19:46
  • 1
    Ok thanks, I did so here: http://stackoverflow.com/questions/23930789/rails-accessing-associated-objects-that-are-several-degrees-apart . Thanks for your help – Isaac Y May 29 '14 at 10:34