【问题标题】:Devise undefined method `build' for nil:NilClass为 nil:NilClass 设计未定义的方法“build”
【发布时间】:2016-03-05 08:45:07
【问题描述】:

我目前正在参加有关 ruby​​ on rails 的在线课程,并且我从头开始学习所有内容,如果我的问题不清楚,请原谅我。这是我的delima,我正在尝试在rails应用程序中的两个模型之间创建一个链接,这就是我到目前为止所拥有的。但是,当我尝试访问 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

【问题讨论】:

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


    【解决方案1】:

    看看这个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 = {})
    

    【讨论】:

      【解决方案2】:

      一对一关联:

      class User < ActiveRecord::Base
        has_one :business
      end
      
      current_user.build_business
      

      或者如果一对多:

      class User < ActiveRecord::Base
        has_many :businesses
      end
      
      current_user.businesses.build
      

      【讨论】:

        猜你喜欢
        • 2017-07-11
        • 2014-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-27
        • 2013-06-30
        相关资源
        最近更新 更多