Vesuvious
Vesuvious

Reputation: 121

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

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

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. 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. I am just really lost how I am breaking it right now.

Upvotes: 1

Views: 72

Answers (1)

Tom Aranda
Tom Aranda

Reputation: 6036

According to the Rails Guide, the has_one association does not have a new method. Try using build_student() instead. In your case, this should work:

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

Upvotes: 2

Related Questions