0
votes

I am setting up an application and I am having issues with ActiveRecord relationships. here is the breakdown.

1. A Client has_many Sites therefore a Site belongs_to Client

class Client
 has_many :sites
end

class Site
 belongs_to :client
end

2. A Site has_many Reports therefore a Report belongs_to Site

class Site
 has_many: reports
end

class Report
 belongs_to :site
end
  1. this is where I am getting stumped.

    A Patrol has_many Hits therefore a Hit belongs_to Patrol

    A Hit belongs_to Site therefore a Site has_many Hits

    a Report belongs_to Site therefore a Site has_many Reports

the problem is setting this last part up not too sure to to layout the models or if a :through relationship is warranted?? Essentially what I am hoping to achieve here is that when an admin sets up a patrol and assigns a site to a hit the user can view the site through the hit show page and generate a new site report than can then be viewed under the client/site show page in the admin table.?

Am I out in outer-space here??

Nesting the client and site was a breeze and i can generate a new report from the site show page, but to streamline report creation for the end user I am hoping to go the above route.. just not sure about how to proceed.

If you require further assistance please let me know ill give you what I can!

Thanks.

EDIT # 1 My Model Structure

This group is nested as a site is built through the client show page
class Client
 has_many :sites
end 

class Site
 belongs_to :client
end

This is where I am having the most troubel, as there is alot going on here at least in my mind. I am open to any suggestions in configuring this..

class PatrolRoute
 has_many :patrol_hits
end

class PatrolHit
 belongs_to :patrol_route
# A PatrolHit Should only have one Site and that site should not be created only selected from a dropdown box of pre-existing sites
end

class Site
belongs_to :patrol_hit
has_many: patrol_reports
end

Class PatrolReport
belongs_to :site
has_many :line_items
end 

class LineItem 
 belongs_to :report
end
1
what is Patrol? another model?Aleksey
ill add all of my modelsShawn Wilson
I just ask about Patrol. It's anotger model or instance of some model listed here?Aleksey
No as of right not it is nothing Patrol is Patrol Route NowShawn Wilson
I added a better model breakdown for you to reviewShawn Wilson

1 Answers

2
votes

It is hard to provide you with exact answer since the whole thing and DB structure are unclear.

One thing that might help you to deal with all those associations is simple:
belongs_to :foo means that model's DB table should have foo_id column.

In your particular case

class PatrolHit
  belongs_to :patrol_route
end

means that patrol_hits table should have columns like

id             
patrol_route_id
...

I think keeping that rule in mind would help you.