0
votes

I'm trying to create a has many through association but I've must have gotten it all wrong.

I believe i got the association code right but when I try to create joined records this is what I get.

1.9.3p194 :001 > d = Day.find(1) Day Load (3.9ms) SELECT "days".* FROM "days" WHERE "days"."id" = ? LIMIT 1 [["id", 1]] => # 1.9.3p194 :002 > d.students.create!(:id => 1) (0.1ms) begin transaction SQL (2.0ms) INSERT INTO "students" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Thu, 18 Apr 2013 12:49:25 UTC +00:00], ["name", nil], ["updated_at", Thu, 18 Apr 2013 12:49:25 UTC +00:00]] (0.8ms) rollback transaction ActiveRecord::UnknownAttributeError: unknown attribute: day_id

Models

# == Schema Information
#
# Table name: students
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Student < ActiveRecord::Base
  attr_accessible :name
  has_many :days, :through => :days_students
  has_many :days_students, :dependent => :destroy, :class_name => "DayStudent"
end

# == Schema Information
#
# Table name: days
#
#  id         :integer          not null, primary key
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Day < ActiveRecord::Base
  #attr_accessible 
  has_many :students, :through => :days_students
  has_many :days_students, :dependent => :destroy, :class_name => "DayStudent"
end

# == Schema Information
#
# Table name: day_students
#
#  id          :integer          not null, primary key
#  students_id :integer
#  days_id     :integer
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#

class DayStudent < ActiveRecord::Base
  attr_accessible :student_id, :day_id
  belongs_to :day
  belongs_to :student
end
1

1 Answers

0
votes

Your attributes in the day_students table should be:

  • day_id
  • student_id