我有一个项目对象的 Backbone.js 集合和模型:
window.Project = Backbone.Model.extend();
window.Projects = Backbone.Collection.extend({
model: Project,
url: '/projects'
});
我已经设置了一个 Rails Controller 来响应 Backbone.js 集合:
class ProjectsController < ApplicationController
def index
render :json => Project.all
end
def create
project = Project.create! params
render :json => project
end
end
索引工作正常,我在网络应用程序中获得了项目列表。问题是,如果我尝试在 Projects 集合上创建模型,我会从服务器收到 500 错误。
服务器端错误信息如下:
Started POST "/projects" for 127.0.0.1 at 2011-08-21 08:27:56 +0100
Processing by ProjectsController#create as JSON
Parameters: {"title"=>"another test"}
Completed 500 Internal Server Error in 16ms
ActiveRecord::UnknownAttributeError (unknown attribute: action):
app/controllers/projects_controller.rb:8:in `create'
我不确定未知属性:操作
指的是什么。
有关信息,我已将 projects_controller
设置为 resources :projects
。我还将 Rails 设置为 ActiveRecord::Base.include_root_in_json = false
。
最佳答案
是的,Rails 总是将 action
和 controller
添加到 params
中。参数来自ActionDispatch::Http::Parameters:
def parameters
@env["action_dispatch.request.parameters"] ||= begin
params = request_parameters.merge(query_parameters)
params.merge!(path_parameters)
encode_params(params).with_indifferent_access
end
end
Returns a hash with the parameters used to form the path of the request. Returned hash keys are strings:
{'action' => 'my_action', 'controller' => 'my_controller'}
所以你不应该这样做 project = Project.create!参数
。您可以采用 update_attributes
路线:
project = Project.new
project.update_attributes params[:model_name]
但这假设您在 params
的子哈希中拥有所需的内容,并且它不会调用您的验证器。默认情况下,Backbone 不会为您的属性命名空间,但您可以覆盖 Backbone.sync 并自行完成。不过,您可能需要进行验证,因此通常应避免 update_attributes
。
最好的选择是从 params
中准确提取您期望的属性。这甚至是Backbone recommended practise :
*(In real code, never use update_attributes blindly, and always whitelist the attributes you allow to be changed.)*
关于ruby-on-rails-3 - 使用 Rails 保存 Backbone.js 模型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7137096/