繁体   English   中英

Rails初学者-如何使此API接受JSON?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM