簡體   English   中英

Rails has_one和has_many

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM