Search code examples
angularjsruby-on-rails-4strong-parametersrails-apingresource

How to send the correct request to my rails-api thanks to ng-resource?


I created an API using the rails-api gem and I have an client app based on angular in which I use ng-resource.

I do think that the request I send to my API should be more like {post=>{"kind"=>"GGG"}} and not {"kind"=>"GGG"} of I have to find a way for my api to work with the request I send now. For now I'm stuck with 400 Bad Request errors and I can't find out how to fix it.

  • Here is my rails controller :

    class PostsController < ApplicationController
      # GET /posts
      # GET /posts.json
      skip_before_filter :verify_authenticity_token, :only => [:update, :create]
    
      def index
        @posts = Post.all
    
        render json: @posts
      end
    
      # GET /posts/1
      # GET /posts/1.json
      def show
        @post = Post.find(params[:id])
    
        render json: @post
      end
    
      # POST /posts
      # POST /posts.json
      def create
        @post = Post.new(post_params)
    
        if @post.save
          render json: @post, status: :created, location: @post
        else
          render json: @post.errors, status: :unprocessable_entity
        end
      end
    
      # PATCH/PUT /posts/1
      # PATCH/PUT /posts/1.json
      def update
        @post = Post.find(params[:id])
    
        if @post.update(params[:post])
          head :no_content
        else
          render json: @post.errors, status: :unprocessable_entity
        end
      end
    
      # DELETE /posts/1
      # DELETE /posts/1.json
      def destroy
        @post = Post.find(params[:id])
        @post.destroy
    
        head :no_content
      end
    
      private
      def post_params
        params.require(:post).permit(:post, :kind)
      end
    end
    
  • Here is my angular controller :

         $scope.postData = {};
         $scope.newPost = function() {
          console.log($scope.postData);
              var post = new Post($scope.postData);
              post.$save($scope.postData);
          }
    
  • Here is my angular factory :

       .factory('Post', function($resource) {
          return $resource('http://localhost:3000/posts');
       })
    
  • In my logs I have :

     Started POST "/posts?kind=GGG" for 127.0.0.1 at 2014-05-26 18:21:21 +0200
     Processing by PostsController#create as HTML
       Parameters: {"kind"=>"GGG"}
     Completed 400 Bad Request in 2ms
    
     ActionController::ParameterMissing (param is missing or the value is empty: post):
       app/controllers/posts_controller.rb:55:in `post_params'
       app/controllers/posts_controller.rb:23:in `create'
    

-


Solution

  • Change the following code:

    def post_params
      params.require(:post).permit(:post, :kind)
    end
    

    To be:

    def post_params
      params.permit(:post, :kind)
    end
    

    And you problem will be fixed.