1
votes

I'm trying to create a teacher table which has a column in it called 'teacher_type_id' i.e. it's a foreign key which is connected to the teacherType table which has three rows, namely 1 => Tutor, 2 => Module Leader and 3 => Lecturer.

My schema.rb file has the following information in it:

create_table "teacher_types", :force => true do |t|
 t.string   "title"
 t.datetime "created_at", :null => false
 t.datetime "updated_at", :null => false
end

create_table "teachers", :force => true do |t|
 t.integer  "teacherType_id"
 t.string   "firstName"
 t.string   "lastName"
 t.datetime "created_at",     :null => false
 t.datetime "updated_at",     :null => false
end

add_index "teachers", ["teacherType_id"], :name => "index_teachers_on_teacherType_id"

The teacher_typ.rb file looks like this:

class TeacherType < ActiveRecord::Base
 has_many :teachers
 attr_accessible :title, :teacher_type_id   (Also tried :teacherType_id)
end

And my teacher.rb file looks like this:

class Teacher < ActiveRecord::Base
  has_one :teacherType
  attr_accessible :firstName, :lastName
end

However, now when I go to my localhost:3000/teacher/new and try to create a new teacher using either "1" or "Tutor" as the TeacherType, however when i submit the form, I always get the same error, which is:

ActiveModel::MassAssignmentSecurity::Error in TeachersController#create

Can't mass-assign protected attributes: teacherType_id
Rails.root: /Users/omar/rails_projects/attendance

Application Trace | Framework Trace | Full Trace
app/controllers/teachers_controller.rb:43:in `new'
app/controllers/teachers_controller.rb:43:in `create'

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"NEJf3bISJsidStVyfdRns0oZ7JzSZ8RqqZSAWgL9hz8=",
 "teacher"=>{"teacherType_id"=>"Tutor",
 "firstName"=>"Jack",
 "lastName"=>"Sparrow"},
 "commit"=>"Create Teacher"}`

Any ideas why that could be? I had a look at the attr_accessible but still to no avail

2
Why is the attr accessible in teacher type? - Dave Newton
Was playing around with the attr_accessible as I read on various forums and questions answered that this solved it. But it doesn't really - omarArroum
But the attr is in teacher, not teacher type. - Dave Newton
Yeah, doesn't that mean that TeacherType is making the teacher_type_id attritube accessible to other models...? Abitike declaring a public variable i thought.... Or am I totally wrong in my thinking - omarArroum
No, it means the model it's declared in is allowing mass-assignment of that attribute--and that apneadiving's answer works should clarify it even further. Think about it--you wouldn't want to set a teacherType's ID from a form, teacherTypes already have an ID. - Dave Newton

2 Answers

3
votes

teacherType_id is being assigned a string in the TeachersController#new view, but it's declared as an integer. Check your view. Plus I'd avoid using names with mixed cases such as teacherType_id...

2
votes

in Teacher:

attr_accessible :firstName, :lastName, :teacherType_id