Problem with creating two objects with one controller action with ruby on rails

108 views Asked by At

I am trying to send one post to a create in a controller and create two objects. For some reason the contoller only will create a company. I did a similair thing in sinatra and it worked. I know that the route is correct and so is the object the post sends.

Conrtoller:

 def index
    stocks = current_user.stocks
    render json: stocks, include: ['company']
  end 
 def create
    company = Comapny.find_or_create_by(name: params["company"])
    stock = current_user.stocks.create(stock_params)
    render json: stock, status: :created
   end

Params:

def stock_params
    params.require(:stock).permit(:name, :price_purchased_at, :number, :info, :restaurant )
  end 

Serializer:

class StockSerializer < ActiveModel::Serializer
  attributes :id, :name, :price_purchased_at, :info, :number, :company

  belongs_to :user
  belongs_to :company
end

I have tried changing the serializer and the params. I have also tried leaving out the company create line to see if it will create the stock but it still won't create a stock.

1

There are 1 answers

0
spickermann On

You ensure in your create that a company with the expected name exists. But you do not pass the found company to the stock creation method. Therefore, the stock creation fails with Company must exist.

Just change your create method to this:

def create
  company = Company.find_or_create_by(name: params['company'])
  stock = current_user.stocks.create!(stock_params.merge(company_id: company.id))

  render json: stock, status: :created
end