简体   繁体   English

Rails has_one和has_many

[英]Rails has_one and has_many

How come when I change my user.rb model to the correct way of has_one :student instead of has_many :students it breaks student controller in my Create method and says that 'new' is an undefined method? 当我将user.rb模型更改为has_one :student而不是has_many :students的正确方法时,为什么会破坏我的Create方法中的学生控制器,并说“ new”是未定义的方法?

user.rb 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 student.rb

class Student < ApplicationRecord
  belongs_to    :user
  has_one   :emergency_contact
  has_one   :vehicle 
end

students_controller.rb 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

I am trying to pass in the current user ID who is logged in using the Devise current_user method and assign it to the student. 我试图传递使用Devise current_user方法登录的当前用户ID,并将其分配给学生。 It works when I change in the user model from has_one :student to has_many :students , and when I change the students controller from current_user.student.new() to current_user.students.new() but that is not correct, because the user has only one student. 当我将用户模型从has_one :student更改为has_many :students ,以及当我将学生控制器从current_user.student.new()更改为current_user.students.new() ,该方法都有效,但这是不正确的,因为用户只有一个学生。 I am just really lost how I am breaking it right now. 我真的迷失了我现在如何打破它。

According to the Rails Guide , the has_one association does not have a new method. 根据Rails指南has_one关联没有new方法。 Try using build_student() instead. 尝试改用build_student() In your case, this should work: 在您的情况下,这应该起作用:

def create
  @student = current_user.build_student(student_params)
  ...
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM