Backbone.js的和Rails - 如何处理来自骨干机型PARAMS? [英] Backbone.js and Rails - How to handle params from Backbone models?
问题描述
在一个标准的Rails控制器,我想创建一个记录是这样的:
In a standard Rails controller, I'd create a record like this:
@user = User.new(params[:user])
这假定了进来表单参数嵌套。
This assumes that the form parameters that come in are nested.
我一直在玩Backbone.js的,我注意到,在默认情况下,骨干不窝参数正常的Rails表单可能的方式,这实际上是我的预期。所以我不知道我该怎么办...
I've been playing with Backbone.js and I noticed that by default, Backbone doesn't nest the parameters the way a normal Rails form might, which is actually something I expected. So I'm wondering what I should do...
我
找出在服务器端,如果它是从骨干网的要求通过观察接受头,等和操纵PARAMS自己,所以我可以保持我的控制器code小:
figure out on the server-side if it's a request from Backbone by looking at accepts headers, etc and manipulate the params myself so I can keep my controller code small:
do_some_params_manipulation_with(params)
@user = User.new(params[:user])
respond_to do |format|
if @user.save
format.html {redirect_to users_url}
format.json {render :json => @user.to_json }
end
end
或者,我该实例中反复code结束了,但可能是从长远来看,更容易维护,每个分支的对象....
Or, do I instantiate the object in each branch which ends up with repeated code but might be more maintainable in the long run....
respond_to do |format|
format.html do
@user = User.new(params[:user])
if @user.save
redirect_to users_url
end
end
format.json do
@user = User.new(params) # and rely on mass-assignment protection
if @user.save
render :json => @user.to_json
end
end
end
还是我通过重写.toJSON方法(我不完全知道怎么做,因为我不知道有足够的了解Backbone.js的还),使其巢PARAMS?修改我的Backbone.js的机型
or do I modify my Backbone.js models by overriding the .toJSON method (which I'm not entirely sure how to do because I don't know enough about Backbone.js yet) so that it nests the params?
在这种情况下,我可以访问应用程序的两侧,但我感兴趣的是别人在做什么。
In this situation, I have access to both sides of the app, but I am interested in what others are doing.
推荐答案
这是很好的时候可以有一般的Rails的形式和骨干形成匹配相对于根节点。这就是为什么在我最后的应用程序,我选择覆盖骨干机型的toJSON方法。
It's nice when you can have the general Rails forms and Backbone forms match with respect to the root node. That's why in my last application I chose to override the Backbone models' toJSON method.
您可以覆盖全局的toJSON方法作为Raimonds Simanovskis建议。但是,即使非干法的做法是没有那么糟糕。样板只有一条线路为每个模型定义:
You could override the global toJSON method as Raimonds Simanovskis suggested. But even the non-DRY way approach isn't so bad. Just one line of boilerplate for each model definition:
// Depends on Underscore.js
User = Backbone.Model.extend({
toJSON: function() {
return { user: _.clone( this.attributes ) }
},
// Your other methods here
});
编辑:修正code样品。很抱歉的错误,我是从翻译的CoffeeScript为JavaScript。
Corrected code sample. Sorry for the errors, I was translating from CoffeeScript to JavaScript.
这篇关于Backbone.js的和Rails - 如何处理来自骨干机型PARAMS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!