gpt4 book ai didi

ruby-on-rails - Rails 3 - 为 belongs_to 模型提供 id 的正确方法

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:34 25 4
gpt4 key购买 nike

我有两个模型:UserTeacher:

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

我的 Controller 中还有一个方法应该创建用户,然后是新老师。但是不能正常工作,因为我没有在那里传递 id

我的 Controller

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

我在 Controller 中有这样的代码,因为我想从用户和老师那里获取所有错误。

错误

["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?

最佳答案

另一种方法是在第一轮简单地创建用户,包括教师角色。然后管理员填写第二个表格,其中包含个人资料详细信息,如果您愿意,可以填写“填写您的个​​人资料”(教师模型仍会包含此内容。)

无论哪种方式,您可能都需要 delegates_to 方法来访问方法 http://apidock.com/rails/v3.1.0/Module/delegate

此外,无论您如何操作,您都可以考虑将 attr_accessible 排除在外,直到它以其他方式正常工作。

但如果你找到一种方法同时创建它们,我将第一个复制你!

关于ruby-on-rails - Rails 3 - 为 belongs_to 模型提供 id 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9720378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com