我试图实现基于backbone.js和rails4的简单演示。为此,我创建了简单的模型:
app.LocationModel = Backbone.Model.extend({
defaults : {
name : "Test name",
description : "Test description",
},
});
稍后在代码的某处,我将模型的纬度和经度从Google标记对象中取出。然后我打电话给模特保存。在Chrome开发工具中,我看到POST请求中的请求有效负载包含以下信息:
{"pos":{"latitude":52.30511992110524,"longitude":16.2103271484375},"name":"Test name","description":"Test description"}
这是正确的。在Rails方面,我尝试接收这些JSON对象并以某种方式持久存储在数据库中:
def create
@location = Location.new(location_params)
if @location.save
render json: @location
end
end
... 其中:
def location_params
puts "test #{params.permit(:name, :description, :pos)}"
params.permit(:name, :description, :pos)
end
测试放置显示:test {"name"=>"Test name", "description"=>"Test description"}
位置数据库表如下所示:
create_table :locations do |t|
t.string :name
t.string :description
t.float :latitude
t.float :longitude
t.timestamps
end
不幸的是,从我不知道的原因来看,这个" pos"信息(纬度和经度)不会保留(为空)。当显示有关从请求获取的参数的信息时,奇怪的事情发生在服务器日志中:
Processing by LocationsController#create as JSON Parameters: {"pos"=>{"latitude"=>52.562995039558004, "longitude"=>16.38336181640625}, "name"=>"Test name", "description"=>"Test description", "location"=>{"name"=>"Test name", "description"=>"Test description"}} Geokit is using the domain: localhost Unpermitted parameters: pos, location test {"name"=>"Test name", "description"=>"Test description"} Unpermitted parameters: pos, location (0.2ms) begin transaction SQL (1.6ms) INSERT INTO "locations" ("created_at", "description", "name", "updated_at") VALUES (?, ?, ?, ?) [["created_at", "2014-08-13 09:28:59.092248"], ["description", "Test description"], ["name", "Test name"], ["updated_at", "2014-08-13 09:28:59.092248"]] (162.1ms) commit transaction Completed 200 OK in 169ms (Views: 0.8ms | ActiveRecord:
163.8ms)
为什么当显示的参数有位置对象=>但没有" pos"信息?我想这也是一个根本原因,为什么会显示有关未经许可的信息" pos"最后这些漫长的& lat不会传递给插入查询
答案 0 :(得分:1)
您的Location
模型具有单独的latitude
和longitude
属性:
create_table :locations do |t|
#...
t.float :latitude
t.float :longitude
#...
end
而不是单个pos
属性。如果你说:
Location.new(:name => '...', :description => '...', :pos => { ... })
然后,您将获得仅Location
和name
属性的description
,因为Location
对pos
一无所知。
如果一切都与您的模型完全匹配,那么您将有更好的时间。您的Backbone模型应该发送:
{
"latitude": 52.30511992110524,
"longitude": 16.2103271484375,
"name": "Test name",
"description":"Test description"
}
并且您的控制器的参数检查应如下所示:
def location_params
params.permit(:name, :description, :latitude, :longitude)
end