[英]Rails has_one and has_many
当我将user.rb
模型更改为has_one :student
而不是has_many :students
的正确方法时,为什么会破坏我的Create
方法中的学生控制器,并说“ new”是未定义的方法?
user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :vehicle
has_one :permit
has_one :faculty
has_one :emergency_contact
has_one :student
end
student.rb
class Student < ApplicationRecord
belongs_to :user
has_one :emergency_contact
has_one :vehicle
end
students_controller.rb
class StudentsController < ApplicationController
before_action :set_student, only: [:show, :edit, :update, :destroy]
.....
def create
@student = current_user.student.new(student_params)
respond_to do |format|
if @student.save
format.html { redirect_to @student, notice: 'Student was successfully
created.' }
format.json { render :show, status: :created, location: @student }
else
format.html { render :new }
format.json { render json: @student.errors, status:
:unprocessable_entity }
end
end
end
我试图传递使用Devise current_user方法登录的当前用户ID,并将其分配给学生。 当我将用户模型从has_one :student
更改为has_many :students
,以及当我将学生控制器从current_user.student.new()
更改为current_user.students.new()
,该方法都有效,但这是不正确的,因为用户只有一个学生。 我真的迷失了我现在如何打破它。
根据Rails指南 , has_one
关联没有new
方法。 尝试改用build_student()
。 在您的情况下,这应该起作用:
def create
@student = current_user.build_student(student_params)
...
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.