-1

I have a simple_form_for that creates an invoice. Through this form, I want the user to be able to create a client that will be associated with that before-mentionned invoice. The current process being to firstly create the client, then associate it to the invoice by selecting it from a collection of created clients when the user create an invoice.

My models :

class Client < ApplicationRecord
  has_many :invoices
end 
class Invoice < ApplicationRecord
  belongs_to :client
  accepts_nested_attributes_for :client, reject_if: :all_blank, allow_destroy: true
end

Invoice controller:

def new
    @invoice = Invoice.new
    @invoice.build_client
end 

def create
    @invoice = Invoice.new(invoice_params)
    @client = @invoice.build_client(params[:invoice][:client_attributes])
    @client.user = current_user
    @client.save
end

And I made sure to update my strong params in Invoice Controller with :

params.require(:invoice).permit(:param1, :param2,client_attributes:[:param1, :param2, :param3, etc..],..)

That being said, when creating an invoice, I ran into an "ActiveModel :: ForbiddenAttributesError", which is set to appears when strong params are not correctly defined. Which, in my case, does not seem to be the case. I found out that adding "params.permit!" in my #Create in the Invoice Controller, allowed me to avoid that error. But that's a trick. It should not be necessary since that's the jobs of the strong params. Has anyone ever came across a similar case, please?

1 Answer 1

-1

Ok, so I figured this thing out. All that was needed to do was to - obviously- save my client before, my invoice. Rather simple, isn't it!

Here is my final Invoice #New #Create

def new
    @invoice = Invoice.new
    @invoice.build_client
end 
def create
  @invoice = Invoice.new(invoice_params)
  @invoice.client.user = current_user
  @invoice.client.save

  if @invoice.save
    redirect_to @invoice
  else
    render :new
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.