Ruby on rails 主干模型应该表示视图还是服务器端资源?
假设我有一个Rails AR模型,如下所示Ruby on rails 主干模型应该表示视图还是服务器端资源?,ruby-on-rails,backbone.js,backbone-model,Ruby On Rails,Backbone.js,Backbone Model,假设我有一个Rails AR模型,如下所示 class User has_one :profile end class Profile belongs_to user has_one :address end class Address belongs_to :profile end 并具有要在客户端构建的用户配置文件视图。现在,我的主干模型应该是什么样子?它是否应该复制Rails/服务器端域模型中的方式?我们有没有一个明确的理由来解释为什么会这样,还是仅仅是主观的 感谢您
class User
has_one :profile
end
class Profile
belongs_to user
has_one :address
end
class Address
belongs_to :profile
end
并具有要在客户端构建的用户配置文件视图。现在,我的主干模型应该是什么样子?它是否应该复制Rails/服务器端域模型中的方式?我们有没有一个明确的理由来解释为什么会这样,还是仅仅是主观的
感谢您的经验分享 为了简单起见,我认为模型应该同时表示服务器端模型和客户端视图状态,通过前面的。保存模型时,服务器将忽略视图状态属性 以下是我使用的工作流的简化示例:
var animal = new View({
initialize: function(){
// define the model and default view state when view is initialized
this.model = new Model({id:3, _edit:false}, {url:'/animals'));
}
, render: function(){
var self = this;
this.undelegateEvents();
this.delegateEvents({
'click [data-trgger]': function(e){
self[$(e.currentTarget).attr('data-trigger')].apply(this);
}
});
var success = function(){
// pass the model to the template engine
self.$el.html( _.template('#edit-animals', {model: self.model}) );
}
// fetch the model from the server when view is rendered
// you could check if the model is already fetched
this.model.fetch({success:success});
}
, onSave: function(){
// save the model then:
this.model.set('_edit', false);
this.render();
}
, onEdit: function(){
this.model.set('_edit', true);
this.render();
}
});
以及模板:
<% if(model.get('_edit')){ %>
<!-- the view is in 'edit' state, show input and save button -->
<div>
<input type="text" name="breed" class="form-control">
</div>
<button class="btn btn-primary" data-trigger="onSave">Save</button>
<% }else{ %>
<!-- the view is in 'read-only' state, show values and edit button -->
<button class="btn btn-default" data-trigger="onEdit">Edit</button>
<div>
<%= model.get('breed') %>
</div>
<% } %>
通常,主干模型和集合应该遵循RESTAPI或任何其他客户端服务器端通信 例如,如果这些ruby模型通过以下方式传递到前端:
GET /api/user/:id
你得到的回应是
[{ profile: { address: "21st str." } },{ profile: { address: "17th str." } }]
你需要一个模型
User = Backbone.Model
Users = Backbone.Collection.extend({
model: User,
url: "/api/user"
});
ProfileModel = Backbone.Model.extend({
url: "/api/profile"
})
但是,如果您在API中执行更复杂的操作,并且API中有更多URL,那么您可以选择最适合与前端客户机交互的结构。例如,如果您的网站根本不需要用户api,并且您使用这些URL将数据传递到前端:
GET /api/profile
您只能有一个模型
User = Backbone.Model
Users = Backbone.Collection.extend({
model: User,
url: "/api/user"
});
ProfileModel = Backbone.Model.extend({
url: "/api/profile"
})
您可以轻松设置地址,如
profile = new ProfileModel();
profile.set('address', '21st str.');
底线
主干网通常应该遵循RESTAPI的URL结构。如果您这样做,您将充分享受使用它的REST Ajax调用的好处—正确地自动配置GET、POST、DELETE、PUT
通常我不会让我的主干应用程序结构遵循数据库模式。这可能会让人头疼,因为你需要创建一种方式,让你的后端Ruby应用程序能够提供与你正在使用的ORM几乎相同的数据库访问。在一些技术上的混乱之后,我们的团队决定走这条路,我一直在等待社区中其他人的做法。就目前的情况或在我们听到更好的解释之前,我认为你的回答是正确的。谢谢你抽出时间KarthikThis看起来对一个小案子没问题。但我有一种感觉,在现实的用例中,我们有许多嵌套的关联/组合,这会变得复杂。尽管如此,我还是很感谢你的时间。谢谢-卡提克