【发布时间】:2011-03-12 00:01:16
【问题描述】:
我有教师、学生和父母模型都属于用户。这样一来,教师可以根据教师的偏好创建可以或不能登录应用程序的学生和家长。 Student 和 Parent 都接受 User 的嵌套属性,因此可以以相同的形式创建 Student 和 User 对象。所有四个模型也属于 Studio,因此我可以按范围进行数据分离。通过查找当前子域,在 application_controller.rb 中设置当前工作室。
在我的学生控制器(实际上是我的所有控制器)中,我使用@studio.students.new 而不是 Student.new 等,将新学生的范围限定到正确的工作室,从而确定正确的子域。但是,嵌套用户不会从其父级获取工作室 - 它被设置为 nil。
我在想我可以在控制器中执行params[:student][:user_attributes][:studio_id] = @student.studio.id 之类的操作,但这需要在用户中执行attr_accessible :studio_id,这很糟糕。
如何确保嵌套的 User 选择与 Student 模型在创建时获得的相同范围?
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
用户.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
【问题讨论】:
标签: ruby-on-rails-3 forms model scope nested