Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby ActiveRecord Basics Migrations and Relationships Relationships

Ralph Johnson
Ralph Johnson
10,408 Points

Can you retrieve a column from a child's parent table?

I have a project for scheduling employees for jobs. It has tables for Jobs, Shifts (which are individual days included in a job), employees, and employee_shifts (the hookup between an employee and a shift, which may contain many other employees). The shifts are to be displayed in a calendar format, with each shift represented by the project name (which is in the Job table), and a check box indicating availability (which is stored in the employee_shift table). How do I, using the Shift as the starting point, access the project name from the Job table? The relationships are: Jobs, has_many :shifts, and Shift belongs_to :job. Despite the fact that the tables are related, I don't seem to be able to go "up" the inheritance ladder to grab an attribute. In other words, how can I get the job.shift.project? or the shift.job.project? This construct throws an error, but I don't know how to express the idea so that it returns the project name. I can get the job.shift, (@job.shifts.first, e.g.) and the job.project, but can't seem to leap over and grab "upwards." ??

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

Is project the name of the column that represents the project's name?

Ralph Johnson
Ralph Johnson
10,408 Points

Yes. Playing around in the console for a bit, I learned a couple things, then slapped my forehead and said, "I could have had a V-8!" (Some folks may be too young to remember what that means..:). So, for instance, Shift.find(6).job.project gave me the project name of the sixth shift in Shifts. In the case I've described, the job instance should be passed to the view page as an argument. So I was asking a question I should have been able to answer (and not bothered anyone) with a little thought and trial and error. I'm just panicking 'cause this is taking too long to figure out. However, it still takes a little Ruby to get where I'm going, since the id of the Shift has to be within the range covered by the job to which it's associated. I've set this up:

scope :matchup, -> { where("job_id = ?", @job.id } 

...and hopefully that will solve THAT problem. As always, thanks very kindly for responding! Coding gets lonely. Conversation helps the sanity.