0

I'm writing a #create method within a controller file that subsequently updates multiple different tables.

Once I create a reservation using reservation#create in Reservation Table, it should update three other tables:
1) quantity_available and quantity_ordered in Menus table
2) meal_credits_left on Account_Summaries table
3) total_number_ordered on Meals table

My Api::ReservationsController looks like this:

 def create
    @user = current_user
    user_summary = @user.account_summary

    @reservation = Reservation.new(
      user_id: params[:reservation][:user_id],
      menu_id: params[:reservation][:menu_id],
    )

    if @reservation.save
      menu = @reservation.menu
      meal = @reservation.meal

      user_summary.update_attributes(
        meal_credits_left: user_summary.meal_credits_left - 1
      )

      menu.update_attributes(
        quantity_available: menu.quantity_available -1,
        quantity_ordered: menu.quantity_ordered + 1
      )

      meal.update_attributes(
        total_number_ordered: meal.total_number_ordered + 1
      )

      render :show
    else
      render json: @reservation.errors.full_messages, status: 422
    end
  end

How do I set up the route to make sure that I can update those attributes in ReservationsController#create?

My routes look like this:

    resources :account_summaries, only: [:create, :update]
    resources :reservations, only: [:index, :create, :update, :destroy]
    resources :menus, only: [:index, :update]
    resources :meals, only: [:index, :update]
Eric Cheon
  • 33
  • 1
  • 6
  • An observation: When making none-atomic updates like that, consider using a transaction of your db support it. – ekampp Nov 26 '19 at 06:26
  • I don't understand why you are asking about routes configuration when your action already does what you say it should do. (btw, I'd use `meal.increment!(:total_number_ordered)` and `user_summary.decrement(:meal_credits_left)` to DRY it a little) – arieljuod Nov 26 '19 at 12:47

1 Answers1

0

You need to set a route specified like below with API Version here it is v1

https://paweljw.github.io/2017/07/rails-5.1-api-app-part-3-api-versioning/

  namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/' do
       namespace :v1 do
          resources :reservations, only: [:create]
       end
  end

and call this method with METHOD: POST

http://api.localhost.com/v1/reservations/create

https://coderwall.com/p/t68tpa/setting-routes-for-rails-api

raj_acharya
  • 665
  • 5
  • 17