Error when trying to access model's parent

I have two database backed models with a one to many relationship. When
I try to access one of the parent’s attributes through the child I get
the following error:

ActiveRecord::StatementInvalid: Mysql::Error: Unknown column
‘staff_members.student_id’ in ‘where clause’: SELECT * FROM
staff_members WHERE (staff_members.student_id = 352) LIMIT 1

Here are my models:

class StaffMember < ActiveRecord::Base
has_many :students

end

class Student < ActiveRecord::Base
has_one :staff_member

end

Given this relationship I wouldn’t think that the staff_members table
would (or should) have a student_id field. The students table does
however have a staff_member_id table which is properly populated.

In my controller I’m setting an instance variable.
@student = Student.find(params[:id])

In the view I’m trying to access the parent’s attribute
<%= @student.staff_member.first_name %>

What am I doing wrong?

Thanks,
Jake

Are you sure “student_id” is the foreign key? I had a similar problem
the other day.

On Feb 14, 5:19 pm, Jake S. [email protected]

A one-to-many relationship is set up as so:

class StaffMember < ActiveRecord::Base
has_many :students

end

class Student < ActiveRecord::Base
belongs_to :staff_member

end

belongs_to( ) declares that the given class has a parent relationship
to the class
containing the declaration - so staffmember is the parent of student

Your student table needs to have a foreign_key called: staff_member_id

I would change your controller as such, so that the logic is in the
controller and not the view:
@student = Student.find(params[:id])
@staff_name = @student.staffmember.first_name

Then in your view
<%= @staff_name%>

Hope this helps -K

Kim wrote:

A one-to-many relationship is set up as so:

class StaffMember < ActiveRecord::Base
has_many :students

end

class Student < ActiveRecord::Base
belongs_to :staff_member

end

Sorry, the “has_one” was a typo. I didn’t setup a FK, I will try that.

Thanks,
Jake

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs