2016-03-05 95 views
0

我目前参加了Ruby on Rails的在线课程,即时通讯从零开始学习所有的东西,所以请原谅我,如果我在我的问题中不清楚。这里是我的delima,我试图在rails应用程序中的两个模型之间创建一个LINK,这是我迄今为止所做的。但是当我尝试访问localhost3000/business/new时,它返回错误提到它的标题。我得出的结论是,这是因为我使用了“has_one:model”类型的关联,而不是“has_many:model”。我希望有人能在这里指出我正确的方向,因为我花了数小时寻找解决方案。设计nil的undefined方法'build':NilClass

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 

回答

1

一to One Association:

class User < ActiveRecord::Base 
    has_one :business 
end 

current_user.build_business 

或者如果一对多:

class User < ActiveRecord::Base 
    has_many :businesses 
end 

current_user.businesses.build