I am new to rails and am trying to connect my rails api for an article (consists of two fields - title and description) to an iOS application. I am trying to send JSON data in a POST request and then save that data in a database. I am wondering how to make my articles_controller accept and save json data.
Here is my code so far:
class ArticlesController < ApplicationController
before_action :set_article, only: [:edit, :update, :show, :destroy]
def index
@all_articles = Article.all
end
def new
@article = Article.new
end
def edit
end
def create
@article = Article.new(article_params)
if @article.save
flash[:notice] = "Article was sucessfully created"
redirect_to article_path(@article)
else
render 'new'
end
end
def show
end
def update
if @article.update(article_params)
flash[:notice] = "Article was successfully updated."
redirect_to article_path(@article)
else
render 'edit'
end
end
def destroy
@article.destroy
flash[:notice] = "Article was successfully deleted."
redirect_to(articles_path)
end
private
def set_article
@article = Article.find(params[:id])
end
def article_params
params.require(:article).permit(:title, :description)
end
end
The above code is able to submit a form on the webpage and save it to my database. I would like to alter it to accept json data from an iOS application and save to the database.
Thank you very much for any help
Make a route for POST method:
In config/routes.rb
match 'accept_post' => 'articles#accept_post', :via => :post
In Articles Controller
def accept_post
// get parameters as usual (like params[:title] etc.)
// do the saving to db
end
Important Note : Make the url publicly accessible. But do your own authentication, so others cannot POST to it.
You can use your existing action in controller (like create ) if you want, just wanna give you an idea about it.
You may need to parse the JSON in controller :
require 'json'
JSON.parse(<json object>)
JSON.parse(response.body)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.