Restangular + rails:未知属性错误

时间:2015-04-12 14:54:34

标签: ruby-on-rails angularjs restangular grape-api

我想用Restangular发出一个补丁请求来更新用户atrributes。所以,写一下:

user.patch(user: user).then(function (result) ...

我在rails中使用葡萄框架,我的控制器看起来像这样:

desc 'Update a user'
    params do
      requires :user, type: Hash, desc: "user attributes" do
        optional :email, type: String, allow_blank: false, regexp: /.+@.+/, documentation: { example: 'example@hubeert.com' }
        optional :password, type: String, allow_blank: false
        optional :firstname, type: String
        optional :lastname, type: String
        optional :city, type: String
        optional :date_of_birth, type: Date
      end
    end

    patch ':id' do
      puts params.to_h
      user = User.find(params[:id])
      user.update(params[:user].to_h)
      user
    end

不幸的是,我的用户模型不具备属性路径,因此rails显示此错误:

ActiveRecord::UnknownAttributeError (unknown attribute: route):
  app/controllers/api/v1/users.rb:44:in `block (2 levels) in <class:Users>'

我该怎么办?在角度或轨道中删除此atrribute?可以用我选择的参数更新模型吗?

1 个答案:

答案 0 :(得分:1)

请记住,最好只使用您希望允许的参数创建/更新记录 - 您可以使用Grape轻松完成此操作。

Grape有一个方便的declared方法,可以接受带有include_missing参数的params params do ... end。因此,您可以编写一个帮助程序来过滤掉def permitted_params @permitted_params ||= declared(params, include_missing: false).to_h end 块中未声明的任何参数:

patch ':id' do
  user = User.find(params[:id])
  user.update(permitted_params[:user])
end

然后在你的控制器中:

Timer t = new Timer();
t.Interval = 1000;
t.Tick += () => (label.Text = /*database grep*/);
t.Start();