Rails nested models and data separation by scope

Posted by jobrahms on Stack Overflow See other posts from Stack Overflow or by jobrahms
Published on 2011-03-12T00:01:16Z Indexed on 2011/03/12 0:10 UTC
Read the original article Hit count: 291

Filed under:
|
|
|
|

I have Teacher, Student, and Parent models that all belong to User. This is so that a Teacher can create Students and Parents that can or cannot log into the app depending on the teacher's preference. Student and Parent both accept nested attributes for User so a Student and User object can be created in the same form. All four models also belong to Studio so I can do data separation by scope. The current studio is set in application_controller.rb by looking up the current subdomain.

In my students controller (all of my controllers, actually) I'm using @studio.students.new instead of Student.new, etc, to scope the new student to the correct studio, and therefore the correct subdomain. However, the nested User does not pick up the studio from its parent - it gets set to nil.

I was thinking that I could do something like params[:student][:user_attributes][:studio_id] = @student.studio.id in the controller, but that would require doing attr_accessible :studio_id in User, which would be bad.

How can I make sure that the nested User picks up the same scope that the Student model gets when it's created?

student.rb

class Student < ActiveRecord::Base
  belongs_to :studio
  belongs_to :user, :dependent => :destroy

  attr_accessible :user_attributes
  accepts_nested_attributes_for :user, :reject_if => :all_blank
end

students_controller.rb

def create
  @student = @studio.students.new
  @student.attributes = params[:student]
  if @student.save
    redirect_to @student, :notice => "Successfully created student."
  else
    render :action => 'new'
  end
end

user.rb

class User < ActiveRecord::Base
  belongs_to :studio

  accepts_nested_attributes_for :studio
  attr_accessible :email, :password, :password_confirmation, :remember_me, :studio_attributes

  devise :invitable, :database_authenticatable, :recoverable, :rememberable, :trackable
end

© Stack Overflow or respective owner

Related posts about ruby-on-rails-3

Related posts about forms