【问题标题】:Parse JSON HTTP post in Rails 3 app?在 Rails 3 应用程序中解析 JSON HTTP 帖子?
【发布时间】:2012-10-26 11:40:42
【问题描述】:

我有一个简单的 Rails 3 示例应用程序,我正在尝试解决如何解析 JSON POST 并将数据插入到我的应用程序数据库中。

我有一个基本的Activity控制器和模型,控制器如下:

class ActivitiesController < ApplicationController
  # GET /activities
  # GET /activities.json
  def index
    @activities = Activity.order('created_at DESC').limit(10)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @activities }
    end
  end

  # GET /activities/1
  # GET /activities/1.json
  def show
    @activity = Activity.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @activity }
    end
  end

  # GET /activities/new
  # GET /activities/new.json
  def new
    @activity = Activity.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @activity }
    end
  end

  # GET /activities/1/edit
  def edit
    @activity = Activity.find(params[:id])
  end

  # POST /activities
  # POST /activities.json
  def create
    @activity = Activity.new(params[:activity])

    respond_to do |format|
      if @activity.save
        format.html { redirect_to @activity, notice: 'Activity was successfully created.' }
        format.json { render json: @activity, status: :created, location: @activity }
      else
        format.html { render action: "new" }
        format.json { render json: @activity.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /activities/1
  # PUT /activities/1.json
  def update
    @activity = Activity.find(params[:id])

    respond_to do |format|
      if @activity.update_attributes(params[:activity])
        format.html { redirect_to @activity, notice: 'Activity was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @activity.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /activities/1
  # DELETE /activities/1.json
  def destroy
    @activity = Activity.find(params[:id])
    @activity.destroy

    respond_to do |format|
      format.html { redirect_to activities_url }
      format.json { head :no_content }
    end
  end
end

我还从我尝试接收来自的 POST 的应用程序中获得了一个示例 JSON 有效负载:

payload {"files":{"changed":[],"removed":[".gitmodules","extensions","extensions/markdown"]},"project":{"permalink":"dans-stuff-2","public_key":"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuB80S+kMN1266LvCEXoU5hmjugcuXko61Hl7uD9VVgMgEOrLSkeYktOPshgCOwjQgGhSMVEHWrSuOddOi+V3rOu3v91jiU3vycRM3nK9GMaOFf+tTn0/4ReUvGOFHeir1vluHCmOAmpqsVhGWkCJY6eJE37muvGdTG4nW/VnpWYCTLfSOeaq5MVx5LU+zYLntvB5PXd7h1k5ROO8lW+5QzGVyHHEvilzJOqESIAWpNtcXGBt7clWpFH4lg2AT7JebYFuHl8Sl4LYzIRegcpg718CWJjrck9/xV6CBTGP520ifU6K0x4JOn/qFzVlqwnxmrPXwawptmCiYiJt3X8Oz DeployHQ.com Key for dans-stuff-2","name":"Dans Stuff","repository":{"port":null,"username":null,"branch":"master","url":"git@codebasehq.com:atech/deploytest/test1.git","scm_type":"git","cached":true,"hosting_service":{"name":"Codebase","url":"http://www.codebasehq.com","commits_url":"http://atech.codebasehq.com/projects/deploytest/repositories/test1/commits/master","tree_url":"http://atech.codebasehq.com/projects/deploytest/repositories/test1/tree/master"}}},"server":{"name":"cybele","server_path":"/home/dan/deploytest","port":22,"username":"dan","use_ssh_keys":true,"last_revision":"2ad223b9dd6d006d69909407ac7df322e35b009b","hostname":"cybele.phoenixdev.co.uk","identifier":"de99437e-da4a-0986-a7ab-e55805261a96","protocol_type":"ssh"},"start_revision":{"timestamp":"2011-11-30T13:48:22+00:00","author":"Dan Wentworth","ref":"a1c1073b85d1662c075d77f5d88be3fd291abd12","message":"nested markdown pathg","email":"dan@atechmedia.com"},"identifier":"9d0f9c21-f242-3966-fcd3-e821a65acd45","end_revision":{"timestamp":"2011-08-30T16:41:32+01:00","author":"Dan Wentworth","ref":"2ad223b9dd6d006d69909407ac7df322e35b009b","message":"arses","email":"dan@atechmedia.com"},"configuration":{"email_notify":true,"notification_addresses":"dan@atechmedia.com","copy_config_files":true},"timestamps":{"completed_at":"2012-01-17T09:22:15Z","duration":null,"queued_at":"2012-01-17T09:22:07Z","started_at":"2012-01-17T09:22:10Z"},"status":"completed"} -------------------------------------------------------------------------------- signature TMjVYhk/+lQigy3hdkgTZjAaaroxAi126XaDzrQ1xWGyMji9oR0F5nfE73Mo kNs7Hk7aY1GQgtDRdBjgPE+C/6etF9nPFXPacWobaxSP35TGOrpoSACNQDAQ Q0wvn0Bm/jMvhBKoQ6YYUSx8KP8nd7VkgQmv4S0cakgixA4LHfg=

因为需要对 URL 进行 POST,所以我想我需要定义一个新方法:

def deploy_receive
   data = JSON.parse(request.body)
end

我不确定的是,从这里去哪里。我如何从 JSON 中挑选属性并将它们放入活动表中的各种属性中?

这样的?

def deploy_receive
   data = JSON.parse(request.body)
   @activity = Activity.new(params[:fault])
   @activity.who = data.author    
end

任何指针将不胜感激!

【问题讨论】:

    标签: ruby-on-rails-3 json http post


    【解决方案1】:

    如果我理解正确,我认为您正在寻找类似下面的内容:

    路由文件

    match '/api/activity/new' => 'activity#deploy_receive', :via => [:post]
    

    活动控制器(假设发布的数据格式正确)

    def deploy_receive      
        @activity = Activity.new(params[:fault])
        if @activity.save
            render json: @activity
        else
            @activity = "error"
            render json: @activity
        end
    end
    

    【讨论】:

    • 关闭。我想要做的是为要发布的 JSON 提供一个 URL。在我们使用的许多应用程序中,我们可以输入一个 URL,当触发示例 jSON 时,该 URL 就会发布。
    • 啊,我明白了。我已经更新了我的答案以反映您的评论。现在,如果您 POST 到 http://yourdomain.com/api/activity/new,它将相应地处理它并返回 JSON 响应。
    【解决方案2】:

    如果我理解正确的话;如果设置了正确的标题,Rails 已经为您完成了这项工作。结帐:POST json to rails server

    【讨论】:

      猜你喜欢
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 2016-10-12
      • 2012-08-03
      • 2013-04-08
      相关资源
      最近更新 更多