0
votes

User model has_many Companies and Company belongs_to a User.

I now want to change this to a user has_one Company and Company has_one/belongs_to association. I have changed the models to look like this:

user.rb

class User < ApplicationRecord
    has_one :company #was has_many
    accepts_nested_attributes_for :company
    devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

company.rb

class Company < ApplicationRecord
    belongs_to  :user
    has_many        :employees, inverse_of: :company
    has_many        :quotes, inverse_of: :company
    accepts_nested_attributes_for :employees, reject_if: :all_blank, allow_destroy: true #, :reject_if => lambda { |e| e.first_name.blank? }
    accepts_nested_attributes_for :quotes, allow_destroy: true

    validates_presence_of :user, :co_name, :co_number, :postcode
    validates :co_name, length: { minimum: 2, message: "minimum of 2 chars" }
    validates :co_number, format: { with: /\A([1-9]\d{6,7}|\d{6,7}|(SC|NI|AC|FC|GE|GN|GS|IC|IP|LP|NA|NF|NL|NO|NP|NR|NZ|OC|R|RC|SA|SF|SI|SL|SO|SP|SR|SZ|ZC|)\d{6,8})\z/,
                message: "must be valid company number" }
    validates :postcode, format: { with: /\A(?:gir(?: *0aa)?|[a-pr-uwyz](?:[a-hk-y]?[0-9]+|[0-9][a-hjkstuw]|[a-hk-y][0-9][abehmnprv-y])(?: *[0-9][abd-hjlnp-uw-z]{2})?)\z/,
                message: "must be valid postcode" }

    enum industry:          [ :financial_services, :architect, :business_consultancy ]
end

and have rake db:reset and have changed this line in my Companies#create method:

@company = current_user.companies.new(company_params)

to

@company = current_user.company.new(company_params)

But I'm getting a

undefined method `new' for nil:NilClass

and I can't see where I'm going wrong. current_user should be available? the has_one association is defined so I should be able to call company.new on it right? I don;t need a foreign_key added to User, or do I?

Can anyone help me with where I'm going wrong? Thank you.

1
Try @company = current_user.build_company(company_params) insteadPavan
Great @pavan, that works now, whats the difference between .build_company and `.company.new' can you tell me? (Put above as answer please and I'll accept. Thanksjbk
I've added my answer :)Pavan

1 Answers

1
votes

undefined method `new' for nil:NilClass

For has_one, you should use build_association method, so

@company = current_user.company.new(company_params)

should be

@company = current_user.build_company(company_params)

Here is a list of all available methods for has_one association