C83 / THP_2.0

0 stars 0 forks source link

Issue09 lesson controller #17

Closed C83 closed 6 years ago

C83 commented 6 years ago

Controller

Serializer :

Add Serializer gem in Gemfile :

## Serializer
gem 'active_model_serializers', '~> 0.10.0

Then, bundle install Generating the serializer for lesson model : rails g serializer lesson After that, you can specify attributes you want render :

attributes :id, :title, :description, :created_at

Now, it's easy because we have no association.

Routes

We use the keyword ressources in the route.rb file :

resources :lessons, except: [:new, :edit]

Testing the last step with rails routes

Controller

Create a controller with this ressource. As read, ApplicationController is the right controller for API.

Error :

We want that an error raises up when params aren't valid. create!() permit that : if validation doesn't work, ActiveRecord::RecordInvalid: Validation failed: raises. Place that in application.rb file :

  # Two errors catched : RecordInvalid and ParameterMissing
  rescue_from ActiveRecord::RecordInvalid, ActionController::ParameterMissing, with: :show_errors

  def show_errors(exception)
    render json: exception, status: 403
  end

Render :

To return, use render json: object, status number. Replace with the correct object who has a serializer. Add the correspondent status (the number or the name).

Test controller :

Some tips :

Closes #9

C83 commented 6 years ago

Corrections done. Big thank you @whois-marvin-42 for your sharp eye !

C83 commented 6 years ago

With the positive review of Marvin. Thank you !