gpt4 book ai didi

ruby-on-rails - 将 JSON 数据发布到 Rails Controller ?

转载 作者:行者123 更新时间:2023-12-03 01:19:48 24 4
gpt4 key购买 nike

我在将 JSON 数据发布到 Rails Controller 以及从 JSON 数据获取字段映射到参数以创建实体时遇到一些问题。

该操作如下所示:

def create
@trip = Trip.new(params[:trip])
if @trip.save
respond_to do |format|
format.json{render :json => @trip, :status => :created, :location => @trip }
end
end
end

这是网络服务器的输出:

Started POST "/trips.json" for 127.0.0.1 at Sat Sep 03 12:37:41 -0400 2011
Processing by TripsController#create as JSON
Parameters: {"title"=>"Charlie"}
AREL (0.5ms) INSERT INTO "trips" ("created_at", "updated_at", "title") VALUES ('2011-09-03 16:37:41.945743', '2011-09-03 16:37:41.945743', NULL)
Completed 201 Created in 15ms (Views: 3.5ms | ActiveRecord: 0.5ms)

正如您所看到的,它将 NULL 插入到标题字段中,我希望它能够从 JSON 数据映射它?

这是 HTTP 请求:

Host    localhost:3000
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:6.0.1) Gecko/20100101 Firefox/6.0.1
Accept */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
Content-Type application/json; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://localhost:3000/trips/new
Content-Length 19
Cookie _tripplanner_session=BAh7ByIQX2NzcmZfdG9rZW4iMWJCVDc0YWNIeHROcmw5VC9ZVEhMdFNlR0dtTWtSVytCL0dwTi9yam1CUUU9Ig9zZXNzaW9uX2lkIiU1NzhlMDAwNmM2N2RkMTE1YTA3M2ZmMzA4NDQ0M2NmOQ%3D%3D--1c2f1fc1d7c1bd147fa1cf9cff47e77c050f51be
Pragma no-cache
Cache-Control no-cache

最佳答案

您的问题是您的 Controller 期望与 trip 相关的参数位于 params[:trip] 中。

将你的 json 更改为

trip: {
title: 'Charlie'
}

我认为这会为你解决这个问题。

即您的参数应类似于 params => {:trip => {:title => 'Charlie}}

关于ruby-on-rails - 将 JSON 数据发布到 Rails Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7294446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com