Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails有一个也有很多_Ruby On Rails_Ruby_Activerecord_Devise - Fatal编程技术网

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

就是这样,我试图找出它是否存在,但却找不到它!非常感谢你!