Ruby on rails Rails有一个也有很多
为什么当我将我的Ruby on rails Rails有一个也有很多,ruby-on-rails,ruby,activerecord,devise,Ruby On Rails,Ruby,Activerecord,Devise,为什么当我将我的user.rb模型更改为正确的has\u one:student而不是has\u many:students时,它会破坏我的Create方法中的学生控制器,并说“new”是一个未定义的方法 user.rb class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :
user.rb
模型更改为正确的has\u one:student
而不是has\u 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
class用户
student.rb
class Student < ApplicationRecord
belongs_to :user
has_one :emergency_contact
has_one :vehicle
end
班级学生
学生控制器.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
class StudentsController
我正在尝试输入使用Desive current_user方法登录的当前用户ID,并将其分配给学生。当我在用户模型中从has\u one:student
更改为has\u many:students
,并且当我将students控制器从current\u user.student.new()
更改为current\u user.students.new()
时,它会起作用,但这是不正确的,因为用户只有一个学生。我真的不知道我现在是如何打破它的。根据,有一个关联没有一个新的方法。尝试改用build\u student()
。在您的情况下,这应该有效:
def create
@student = current_user.build_student(student_params)
...
end
就是这样,我试图找出它是否存在,但却找不到它!非常感谢你!