Iphone 在Rails 4中构建JSON API

Iphone 在Rails 4中构建JSON API,iphone,ruby-on-rails,json,Iphone,Ruby On Rails,Json,如何为添加帖子构建JSON API。我正在创建Rails应用程序,并使用JSON API将其与iphone应用程序连接。用户可以从应用程序添加Blog/Post,这样我就可以在rails数据库中添加Blog数据,如标题、文本和图像(使用新方法)。您可以让控制器返回JSON,方法如下: class ProjectsController < ApplicationController def index respond_to do |format|

如何为添加帖子构建JSON API。我正在创建Rails应用程序,并使用JSON API将其与iphone应用程序连接。用户可以从应用程序添加Blog/Post,这样我就可以在rails数据库中添加Blog数据,如标题、文本和图像(使用新方法)。

您可以让控制器返回JSON,方法如下:

class ProjectsController < ApplicationController
    def index
        respond_to do |format|
            format.json { render json: Project.all }
        end
    end

    def show
        respond_to do |format|
            format.json { render json: Project.where(name: params[:name])}
        end
    end
end
class ProjectsController
这实质上是将rails转变为JSON API。确保将模型属性添加到活动::模型::序列化程序中

class ProjectSerializer < ApplicationSerializer
  attributes :id, :name, :description, :imgUrl, :deployUrl
end
class ProjectSerializer
类ApiController

如果我点击网址www.localhost:3000/api/addpatient.json?name=test&gender=male&date\u of_birth=10/02/2010&contact\u no=58475896&billing\u id=25&medicine=48,那么我仍然有一个问题,那就是永远不要添加帖子。这很完美,但它是用来显示单个帖子的列表和详细信息的。希望从iphone应用程序中获取数据并添加新帖子。我认为这是因为您正在执行Patient.new而不是保存它。您需要执行@patient.save!之后。它保存患者,但所有字段均为空,只创建了post的ID。尝试替换。新建为。createIt show me{“ID”:5,“created_at”:“2015-02-02T19:29:08.951Z”,“name”:null,“hospitaladmin_ID”:null,“性别”:null,“出生日期”:null,“contact_no”:null,“billing_ID”:null,“出院状态”:null,“医师”:null,“更新的_at”:“2015-02-02T19:29:08.951Z”}当我点击www.localhost:3000/api/addpatient.json?name=test&gender=male&date\u of_birth=10/02/2010&contact\u no=58475896&billing\u id=25&medicine=48 url
class ApiController < ApplicationController
  respond_to :json
   def patient
   @patients = Patient.all
   respond_with(@patients)
 end
def disease
 @diseasecode = Diseasecode.all
 respond_with(@diseasecode)
end
def addpatient
  @patient = Patient.new(params[:id])
  flash[:notice] = 'Patient was successfully created.' if @patient.save
  respond_with(@patient)
end    
def patient_params
  params.require(:patient).permit(:name, :gender, :date_of_birth, :contact_no, :billing_id, :physician)
end
end