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