0

I have a form where I need to create two objects: sale and organization. This happens inside sales_controller.

For brevity's sake, the models and their attributes are:

sale
  amount (integer)
  organization_id (uuid)

organization
  name (string)

sale belongs_to organization
organization has_many sales

Sales Form

That is what the sales new should look like. It has an input for sales, which user will enter, and it also has an input for Organization name, which user will input. Upon submission, user will have created a new sale (plus created a new organization, associated to that sale).

I am trying to figure out what is the best practice for create method inside sales_controller.

  def create
    @sale = Sale.new(sale_params) #assume sale_params permits organization_id and amount
    @organization = Organization.create(params[:name])
    #@sale.organization_id = @organization.id
    if @sale.save
      render json: @sale
    else
      render json: sale, status: :unprocessable_entity
    end
  end

@organization = Organization.create(...) does not feel right. Is there a way to do multiple object submission the "Rails"-way?

1
  • An old article but the following should help: webuild.envato.com/blog/… You don't actually need Virtus but the article will give you the gist of wrapping up the validations etc. Commented Apr 19, 2017 at 20:22

1 Answer 1

1

Since you may already have created an Organization on a previous sale you could use:

@organization = Organization.find_or_create_by(name: params[:name])

and then continue by associating the sale.organization_id. You will need to have a uniqueness constraint on Organization.name as well.

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.