设计自定义控制器不以嵌套形式创建记录

时间:2014-08-18 11:00:35

标签: ruby-on-rails ruby devise

这很有效,但我在某个地方做了一些改变,现在无法让它发挥作用。我有一个嵌套的表单来创建一个公司以及使用Devise的第一个联系人。正在创建公司记录,但未创建联系人(设计模型)。如果我创建公司然后向公司添加联系人,则会创建联系人,因此我非常确定控制器是否正常工作。需要另一组眼睛来发现我的错误。

错误: CompaniesController中的RuntimeError #create 无法找到nil的有效映射

CompaniesController(相关方法):

  class CompaniesController < ApplicationController
  before_action :set_company, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_contact!, only: [:index, :show, :edit, :update, :destroy]



   # GET /companies/new
  def new
   @company = Company.new
   @company.contacts.build
  end


  # POST /companies
  # POST /companies.json
  def create
    @company = Company.new(company_params)
    respond_to do |format|
      if @company.save
        sign_in(@company.contacts.first)
        format.html { redirect_to @company, notice: 'Company was successfully created.' }
        format.json { render action: 'show', status: :created, location: @company }
      else
        format.html { render action: 'new' }
        format.json { render json: @company.errors, status: :unprocessable_entity }
      end
    end
  end

    # Never trust parameters from the scary internet, only allow the white list through.
    def company_params
      params.require(:company).permit(:name, :legal_entity, :KVK_number, :VAT_number, :KVKdoc, contacts_attributes:[:first_name, :last_name, :address, :phone, :email, :postcode, :password] )
    end
  end

联系人注册控制器:

class Contacts::RegistrationsController < Devise::RegistrationsController
# This is a custom controller that inherits from the standard Devise Registration Controller. 
# This controller is used as the user is added to the existing account not it's own account.

# Skips the standard Devise authentication filter to allow for an active user session to create a user recorod.
skip_before_filter :require_no_authentication

# Custom method to ensure that the user on the page has an active session to ensure that the account is accessable.
before_filter :has_current_contact


# Create method is just a call to the standard Devise create method
def create
  super
end

protected

# Stop the user sessisons from being switched to the new user
def sign_up(resource_name, resource)
  true
end

# Test to see that the person on the page has an active session
def has_current_contact
  if current_contact.nil?
    redirect_to root_path, alert: 'You need to be logged in to do this!' 
  end
end

# Sets the permited params for the registration. Inherits the standard devise parameters defined in the 
# application controller and merges the account id of the current user.
def sign_up_params
  devise_parameter_sanitizer.sanitize(:sign_up).merge(company_id: current_contact.company_id)
end

我可以看到代码在尝试找到公司的联系人时会抛出错误并登录,因为如果没有创建联系人它找不到联系人,但是无法弄清楚为什么它不是创建。

帮助?

0 个答案:

没有答案