工作流程或 AASM 等 gem 的最佳实践
如果您想更新所有属性,但还需要工作流程/AASM 回调才能正确触发,我想知道你们如何在控制器中使用工作流程或 AASM gem。
目前,我这样使用它:
class ModelController < ApplicationController
def update
@model = model.find(params[:id])
if params[:application]['state'].present?
if params[:application]['state'] == "published"
@model.publish!
end
end
if @model.update_attributes(params[:application]); ... end
end
end
感觉不对,什么是更好的解决方案?
i would like to know how you guys use the workflow or the AASM gem in the controller if you want to update all attributes, but also need the workflow/AASM callbacks to fire properly.
currently, i use it like this:
class ModelController < ApplicationController
def update
@model = model.find(params[:id])
if params[:application]['state'].present?
if params[:application]['state'] == "published"
@model.publish!
end
end
if @model.update_attributes(params[:application]); ... end
end
end
that does not feel right, what would be a better solution ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我通常定义多个操作来处理从一种状态到另一种状态的转换,并具有明确的名称。在你的情况下,我建议你添加一个
publish
操作:在你的
routes.rb
中声明:现在你的路线准确地反映了故事发生的情况:
/stories /1234/发布
I usually define multiple actions that handle the transition from one state to another and have explicit names. In your case I would suggest you add a
publish
action:Declare that in your
routes.rb
:Now your route reflects exactly what happens to a story:
/stories/1234/publish
您可以覆盖模型 aasm_state setter (或我的示例中的 status ),以便它可以接受事件名称。然后我们检查它是否是一个有效的事件,然后检查转换是否有效。如果不是,我们将添加正确的错误消息。
请求规格 型号
规格
型号
You can override the models aasm_state setter (or status in my example) so it can accept event names. Then we check to see if it's a valid event then check to see if the transition is valid. If they are not we add the correct error message.
A request spec
The Model Spec
The model
这是一件小事,但如果该东西不存在,则哈希返回 nil,因此您可以删除对 Present 的调用吗?
当然,我知道这不是你要问的。一种替代方法是在模型中放置一个 before 过滤器,并在那里检查状态。这会让你的控制器对你的状态的底层存储视而不见。
顺便说一句,我们在这里使用 AASM,我喜欢它:)
It's a small thing but a hash return nil if the thing is not present, so you could remove the call to present?
I realize that's not what you're asking, of course. One alternative is to put a before filter in the model and do your check for status there. That leaves your controller blind to the underlying storage of your status.
On a side note, we use AASM here and I love it :)
我希望我的模型在更新后返回新状态,这是我能想到的最简单的方法,而无需控制器中的大量“脂肪”,并且如果您的工作流程发生变化,它会让前进变得更容易:
I wanted my model to return the new state after being updated, and this was the easiest way I could think to do this without a lot of "fat" in the controllers, and it makes it easier going forward if your workflow changes: