ThinkTeamwork
ThinkTeamwork

Reputation: 594

how to create record via POST (using POSTMAN)

i'm brand new to rails and did the getting started of guides.rubyonrails.org and now i'm facing a problem with creating a record.

I try to send this json: { "title": "someTitle", "text": "someText" }

to http://www.justatest/articles.json

My Model only has this title and text field as attribute defined.

Route is setup too. And my controller create method looks like that:

  def create
    @article = Article.new(article_params)

   if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  private
    def article_params
      params.require(:article).permit(:title, :text)
    end

I've set POSTMAN to method POST when doing the request but i get this error message: ActionController::ParameterMissing in ArticlesController#create param is missing or the value is empty: article

Upvotes: 1

Views: 1785

Answers (2)

ianks
ianks

Reputation: 1768

In order for this to work, you must set the ContentType headers to be 'application/json', and the relevant fields for creating your record.

Upon receiving this request, Rails recognizes the headers as JSON, and then parses the JSON into the 'params' we all know and love.

Here is a link some of the source in Rails that deals with this.

Upvotes: 2

MurifoX
MurifoX

Reputation: 15089

I believe the json need to be like:

{ article: { title: "someTitle", text: "someText" } }

The method article_params tries to find a key named article, and your json don't have it.

Upvotes: 2

Related Questions