[英]Rails beginner - How to make this API accept JSON?
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. 我是Rails的新手,正在尝试将我的Rails api(包含两个字段(标题和描述))连接到iOS应用程序。 I am trying to send JSON data in a POST request and then save that data in a database. 我正在尝试在POST请求中发送JSON数据,然后将该数据保存在数据库中。 I am wondering how to make my articles_controller accept and save json data. 我想知道如何使我的article_controller接受并保存json数据。
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. 我想更改它以接受来自iOS应用程序的json数据并保存到数据库。
Thank you very much for any help 非常感谢您的帮助
Make a route for POST method: 为POST方法创建路由:
In config/routes.rb 在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. 重要说明 :将该URL公开访问。 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. 您可以根据需要在控制器中使用现有操作(例如create ),只是想给您一个想法。
You may need to parse the JSON in controller : 您可能需要在controller中解析JSON :
require 'json'
JSON.parse(<json object>)
JSON.parse(response.body)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.