为什么当我将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
endstudent.rb
class Student < ApplicationRecord
belongs_to :user
has_one :emergency_contact
has_one :vehicle
endstudents_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我正在尝试传递当前的用户ID,该用户ID是使用assign current_user方法登录的,并将其分配给学生。当我将用户模型从has_one :student更改为has_many :students时,以及当我将学生控制器从current_user.student.new()更改为current_user.students.new()时,这是有效的,但这是不正确的,因为用户只有一个学生。我真的很迷茫我现在是怎么打破它的。
发布于 2017-10-26 17:38:18
根据导轨,has_one关联没有new方法。尝试使用build_student()代替。就你的情况而言,这应该是可行的:
def create
@student = current_user.build_student(student_params)
...
endhttps://stackoverflow.com/questions/46960441
复制相似问题