I have three Models setup with the following associations
class User < ActiveRecord::Base
has_many :faculties
has_many :schools, :through => :faculties
end
class School < ActiveRecord::Base
has_many :faculties
has_many :users, :through => :faculties
end
class Faculty < ActiveRecord::Base
belongs_to :user
belongs_to :school
end
and in my controller i go to create a school and assign the user
class SchoolsController < ApplicationController
def create
@school = current_user.schools.build(params[:school])
...
end
end
When I login and submit the form the flash displays success, but the association doesn’t build on the join table.
I tried it inside the apps console and it builds the association just fine.
I’ve been stuck on this for a couple days now and I just cannot figure out what I am missing. Thank in advance for any and all advice
Two things: If the
schoolsassociation is:throughahas_manyassociation, you will have to select which parent theSchoolexists through.So, for instance, if you were to nest
Schoolresources underusersas in/users/:id/faculties/:idyou could create a school viacurrent_user.faculties.find(params[:faculty_id]).schools.build(params[:school]).saveBased on the example code, it looks like the fundamental problem is that the
has_many xxx, :throughsyntax is being used without specifying the id of thefacultiesrecord. Remember two things: 1) ActiveRecord doesn’t natively support composite primary keys, and 2) you must call #save on associated records created using #build. If you remember these, you should be fine.