Rails has_one和has_many

时间:2017-10-26 17:30:20

标签: ruby-on-rails ruby activerecord devise

为什么当我将user.rb模型更改为has_one :student而不是has_many :students的正确方式时,我的Create方法会破坏学生控制器,并说&#39 ;新'是一种未定义的方法?

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()但这不正确时,它会起作用,因为用户只有一个学生。我现在真的很失落,我现在正在打破它。

1 个答案:

答案 0 :(得分:2)

根据Rails Guidehas_one关联没有new方法。请尝试使用build_student()。在你的情况下,这应该工作:

def create
  @student = current_user.build_student(student_params)
  ...
end
相关问题