0

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

2
  • can you show your current_user method? Commented Jan 14, 2012 at 8:14
  • can you show the log of what happens when the create action happens? Commented Jan 14, 2012 at 8:45

2 Answers 2

1

The build method does not save the object. You need to explicitly call @school.save.

Sign up to request clarification or add additional context in comments.

Comments

0

Two things: If the schools association is :through a has_many association, you will have to select which parent the School exists through.

So, for instance, if you were to nest School resources under users as in /users/:id/faculties/:id you could create a school via current_user.faculties.find(params[:faculty_id]).schools.build(params[:school]).save

Based on the example code, it looks like the fundamental problem is that the has_many xxx, :through syntax is being used without specifying the id of the faculties record. 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.