mardi 24 novembre 2015

ActiveRecord::RecordNotFound in CustomersController#new Couldn't find Business without an ID

so I have looked at other instances of this error in other questions on SO and none seem to be helpful. So, my authentication system should allow a Business to sign up, and allow a user to sign up under their business. However, I'm getting a "couldn't find business without ID" error.

class CreateUsers < ActiveRecord::Migration
  def change


    create_table :users do |t|

      t.references :company, foreign_key: true


      t.timestamps
      t.string :first_name
      t.string :last_name

      t.string :email
      t.string :password_digest
      t.string :remember_digest
      t.string :role

    end


class CustomersController < ApplicationController

  def new

    set_business

    @customer = @business.customers.create(user_params)

  end

  def create

    @customer = Customer.new(customer_params)
    @customer.save!
    session[:customer_id] = @customer.id
    redirect_to '/'
  rescue ActiveRecord::RecordInvalid => ex
    render action: 'new', alert: ex.message
  end

  private
  def customer_params

    params.require(:customer).permit(:first_name, :last_name, :business_no, :email, :password_digest, :business_id) 
  end

  def set_business

    @business = Business.find (params[:business_id])

  end



HTML snippet: Customer.new.html.erb

<h1>Sign Up</h1>

      <%= form_for(@customer) do |f| %>
          <%= f.label :first_name %>
          <%= f.text_field :first_name, :placeholder => "First name" %>
          <%= f.label :last_name %>
          <%= f.text_field :last_name, :placeholder => "Last name" %>
          <%= f.label :email %>
          <%= f.email_field :email, :placeholder => "Email" %>
          <%= f.label :company_id %>
          <%= f.collection_select :business_id, Business.all, :id, :name %>
          <%= f.password_field :password_digest, :placeholder => "Password" %>
          <%= f.submit "Create Account", class: "btn-submit" %>
      <% end %>



class Business < ActiveRecord::Base
  has_many :customers

end

class Customer < ActiveRecord::Base
  belongs_to :business
end

How am I supposed to define the @business variable without getting this error so that a user can sign up under their business? I want them to select from a list of available companies on the form, which will then link them in the database when the user signs up. What am I doing wrong? I am very new to Ruby and I may need some good explanation to why this is happening.

thank you for your time :)

Aucun commentaire:

Enregistrer un commentaire