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 %>
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