首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails has_one和has_many

Rails has_one和has_many
EN

Stack Overflow用户
提问于 2017-10-26 17:30:20
回答 1查看 70关注 0票数 1

为什么当我将user.rb模型改为正确的has_one :student方式而不是has_many :students时,它破坏了Create方法中的学生控制器,并说'new‘是一个未定义的方法?

user.rb

代码语言:javascript
复制
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

代码语言:javascript
复制
class Student < ApplicationRecord
  belongs_to    :user
  has_one   :emergency_contact
  has_one   :vehicle 
end

students_controller.rb

代码语言:javascript
复制
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()时,这是有效的,但这是不正确的,因为用户只有一个学生。我真的很迷茫我现在是怎么打破它的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-26 17:38:18

根据导轨has_one关联没有new方法。尝试使用build_student()代替。就你的情况而言,这应该是可行的:

代码语言:javascript
复制
def create
  @student = current_user.build_student(student_params)
  ...
end
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46960441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档