I got a problem, i’ve got two models
class Department < ActiveRecord::Base
belongs_to :school
has_many :courses
end
class Course < ActiveRecord::Base
has_many :users
has_many :departments
end
My Migrations
class CreateCourses < ActiveRecord::Migration
...
t.string :course_name
t.string :course_code
t.integer :department_id
...
class CreateDepartments < ActiveRecord::Migration
t.string :department_name
t.integer :department_duration
t.string :department_code
t.integer :school_id
Please how would i fetch a department’s name that a course belongs to, this is what i have
<% @courses.each do |course| %>
<%= course.department_name %>
gives
undefined method `department_name' for #<Course:0x43bb280>
Thank’s for any help
From your migrations it looks as if your Course model should have a
belongs_to :departmentstatement instead of thehas_many :departmentsstatement.Assuming that’s what you meant, the reason you get that specific error message is because your course model doesn’t have a department name (that would be weird right? it’s a course, not a department).
It does however belong to a department, and the department has a name. That way, you could write your code like so:
This will get the relevant department from the course and then ask the department for it’s name.
If you do something like this, it’s also advisable to make sure to include the departments in your database query (in the appropriate controller). Otherwise you’ll end up with code that runs at least one database query for each iteration of that above loop.
Also, I would just call the column for the department name
name, since it belongs in a separate table. This way you would writecourse.department.nameinstead ofcourse.department.department_name.