Gem Grape 有什么办法一次性更新所有参数?

wuwx · 2014年02月13日 · 最后由 kingtami 回复于 2015年08月21日 · 3171 次阅读

1,希望 post 的时候可以直接调用

@topic = Topic.new(params)
@topic.save

这种方式直接一次性地提交

2,希望 put 的时候也可以比较方便地更新

@topic = Topic.find(params[:id])
@topic.update(entry_params)
@topic.save

目前是一个字段 一个字段地更新,还得写一堆 if 语句判断这个字段有没有被设置 假如某些字段没有设置的话,而强制更新就可能原来有值后来变成 null 了

大家都是怎么解决这个问题的哇?

update(attributes) Updates the attributes of the model from the passed-in hash and saves the record

只会更新指定的属性,不会把不指定的属性默认设置成 nil

如果遇到了这样的问题,可以先 debugger 一下看看,entry_params 传递过来的到底是什么值。另外看起来你是写了 entry_params 的 helper 方法吧,检查一下自己的这个 helper 写的正确吗

我写的那个 update(attributes) 是 rails 的 controller 里的写法呀,不是 grape 里的写法 在 grape 里我是一个一个属性写的,感觉有点笨拙,所以想找个方便的写法

那就直接用 active record 不就行了?

asp.net mvc 里面有 Model banding 可以直接把 post 过来的数据转化成类。。。

rails 里面貌似每次都用 param

#2 楼 @wuwx 我给你的回复,就是直接复制 Rails 的帮助文档。我了解你说的 update(attributes) 是 rails 的用法。所以我说请检查一下 entry_params 这块你是怎么写的。

ActiveRecord 就是 update_attributes 啊,是用 ActiveRecord 吗?

#7 楼 @Rei 如果直接 update_attributes 的话,不就有可能会恶意传入 admin 这种参数,字段不就被恶意更新了么?

#8 楼 @wuwx 单就你这句话而言 update_attributes 和 update 没区别。

请看下面的文档说明

update(attributes)

Updates the attributes of the model from the passed-in hash and saves the record, all wrapped in a transaction. If the object is invalid, the saving will fail and false will be returned.

Also aliased as: update_attributes

你能加个断点,把 entry_params 打印出来看看么。

#8 楼 @wuwx Rails 在没有 strong_parameters 之前用 Hash#slice(ActiveSupport)过滤 params。

我觉得,如果用另一个 Framework 希望实现 Rails 的功能,那么不如就用 Rails。

#10 楼 @Rei 看来这个 slice 可能是我需要的!感谢!

我想请教一下,你这部分代码怎么处理的?我现在也是遇到这个情况...貌似搜索能力不足...还没找到解决方案,新手~~望谅解

需要 登录 后方可回复, 如果你还没有账号请 注册新账号