[英]Rails beginner - How to make this API accept JSON?
我是Rails的新手,正在嘗試將我的Rails api(包含兩個字段(標題和描述))連接到iOS應用程序。 我正在嘗試在POST請求中發送JSON數據,然后將該數據保存在數據庫中。 我想知道如何使我的article_controller接受並保存json數據。
到目前為止,這是我的代碼:
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
上面的代碼能夠在網頁上提交表單並將其保存到我的數據庫中。 我想更改它以接受來自iOS應用程序的json數據並保存到數據庫。
非常感謝您的幫助
為POST方法創建路由:
在config / routes.rb中
match 'accept_post' => 'articles#accept_post', :via => :post
在文章控制器中
def accept_post
// get parameters as usual (like params[:title] etc.)
// do the saving to db
end
重要說明 :將該URL公開訪問。 但是,請執行您自己的身份驗證,以便其他人無法對其進行發布。
您可以根據需要在控制器中使用現有操作(例如create ),只是想給您一個想法。
您可能需要在controller中解析JSON :
require 'json'
JSON.parse(<json object>)
JSON.parse(response.body)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.