为nil设计未定义的方法`build':NilClass

时间:2016-03-05 08:45:07

标签: ruby-on-rails ruby ruby-on-rails-3 devise

我目前正在注册一个ruby on rails的在线课程,我现在从头开始学习一切,如果我不清楚我的问题,请原谅我。这是我的delima,我试图在rails应用程序中创建两个模型之间的LINK,这是我到目前为止所拥有的。但是,当我尝试访问localhost3000 / business / new时,它返回错误提到它的标题。我得出的结论是,由于我使用的是“has_one:model”类型的关联,而不是“has_many:model”。我希望有人可以指出我在正确的方向,因为我花了几个小时寻找没有解决方案。

class BusinessesController < ApplicationController
  before_action :set_business, only: [:show, :edit, :update, :destroy]
  //edited for clarity
  def new
    @business = current_user.business.build  //The line that returns a undefined method for nil class
  end

  def edit
  end

  def create
    @business = current_user.business.build(business_params)

    if @business.save
      redirect_to @business, notice: 'Business was successfully created.' 
    else
      render "new"
    end
  end

设计用户模型

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :buzzs, dependent: :destroy
  has_one :business, dependent: :destroy
end

商业模式

class Business < ActiveRecord::Base
    belongs_to :user
end

2 个答案:

答案 0 :(得分:2)

看看这个http://guides.rubyonrails.org/association_basics.html#has-one-association-reference。 您应该使用build_business代替business.build

4.2.1 has_one

添加的方法

当您声明has_one关联时,声明类会自动获得与该关联相关的五个方法:

association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})

答案 1 :(得分:1)

一对一协会:

class User < ActiveRecord::Base
  has_one :business
end

current_user.build_business

或者如果一对多:

class User < ActiveRecord::Base
  has_many :businesses
end

current_user.businesses.build