我有两个型号:用户和教师:的Rails 3 - 正确的方式给ID为belongs_to的模型
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :user_login,
:user_role,
:password,
:teacher_attributes
has_one :teacher
accepts_nested_attributes_for :teacher
end
# Table name: teachers
#
# id :integer not null, primary key
# user_id :integer
# teacher_last_name :string(255)
# teacher_first_name :string(255)
# teacher_middle_name :string(255)
# teacher_birthday :date
# teacher_sex :string(255)
# teacher_category :string(255)
# created_at :datetime
# updated_at :datetime
class Teacher < ActiveRecord::Base
attr_accessible :teacher_last_name,
:teacher_first_name,
:teacher_middle_name,
:teacher_birthday,
:teacher_sex,
:teacher_category
belongs_to :user
end
我也有我的控制器的方法,它应该创建用户,然后新教师。但不能正常工作,因为我没有通过id
那里。
我控制器
class AdminsController < ApplicationController
def create_teacher
user_errors, teacher_errors, redirect_path = nil, nil, nil
params[:user][:user_role] = "teacher"
user = User.new(params[:user]) #Problem is here
if user.save
redirect_path = admins_users_of_system_path
flash[:success] = "Teacher created!"
else
redirect_path = admins_new_teacher_path
user_errors = user.errors.full_messages.to_sentence
teacher_errors = user.teacher.errors.full_messages.to_sentence if user.teacher
end
errors_arr = [user_errors, teacher_errors].compact
flash[:error] = errors_arr if errors_arr.present?
redirect_to redirect_path
end
end
我在控制器这样的代码,因为我想抓住从用户和老师的所有错误。
错误
["Teacher user can't be blank", "User can't be blank"]
utf8: ✓
authenticity_token: Hsw9BGOMb37cku6R2aAZsXkYaU5DFZqlUML4yZjqxI0=
user: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
teacher_attributes: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
teacher_last_name: Popov
teacher_first_name: Igor
teacher_middle_name: Yurevich
teacher_sex: m
teacher_birthday: 28.08.1991
teacher_category: Something 1
user_login: schoolh_MXWTQ
password: eviRDyalXnHlK6q
user_role: teacher
commit: Создать
controller: admins
action: create_teacher
我怎样才能建立一个老师和在同一时间正确的用户?我应该如何传递它一个ID?
你有什么错误?你的观点是什么样子? – 2012-03-15 13:23:07
在我的文章中添加了错误文字。 – ExiRe 2012-03-15 13:26:30
您是否从现有用户创建教师?或者你也在这里创建用户?我的意思是,是否将用户转变为老师? – 2012-03-15 13:33:55