许多导轨模型具有相同的标志。最佳实践是什么?
其中一个矿井轨道项目有许多型号带有相同的标志:已批准。 我不喜欢管理这么多模型的“已批准”标志,并且我正在寻求一个 DRY 解决方案。 我找到了一些插件,例如 flag_shih_tzu 或 can_flag,但我认为它们仅适用于模型。
您知道一些可以同时标记多个模型的插件吗? 我认为我一个好的解决方案(没有插件)应该使用多态关联,你同意吗?
非常感谢, 亚历山德罗
One of mine rails projects has many models with the same flag: approved.
I don't like to manage the flag 'approved' for so many models, and I am seeking a DRY solution.
I have found some plugin like flag_shih_tzu or can_flag, but I think they work only with a model.
Do you know some plugin to flag many models at once ?
I think that I a good solution (without plugin) should use the polymorphic associations, do you agree ?
many thanks,
Alessandro
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您正在寻找一种将所有函数存储在一个位置,但可以从所有可标记模型访问它们的方法,我建议为它们编写一个 mixin。例如,在 lib/approved.rb 中,您可以拥有以下模块:
然后只需将 mixin 包含在需要这些功能的所有模型中即可:
希望有帮助!
If all you're looking for is a way to store all the functions in a single place, but have them accessible from all your flagable models, I'd recommend writing a mixin for them. For example, in lib/approved.rb, you could have the module:
And then it's just a matter of including the mixin in all the models that need those functions:
Hope that helps!
我的应用程序中也有类似的问题,我们有 10 个左右的模型,所有模型都需要批准,并且不想到处复制代码。在我们的例子中,我们使用
transitions
作为工作流程 gem,因此我们没有使用approved
标志,而是使用字符串列state
。需要批准的模型如下所示:
然后我们有一个如下所示的工作流程:
所以这里发生的是我们创建了一个模块,您可以将其视为不属于任何地方的匿名代码段(阅读有关模块的更多信息以了解为什么这是一个糟糕的描述),然后我们将其包含在混合功能的类中。现在我们的评论类有了审批工作流程!
在您的情况下,假设您要保留批准标志,您可以添加默认验证、一些方法,例如
approve!(user)
或查询范围。我希望这有帮助。
I have a similar problem in my application, we have 10 or so models that all require approval and didn't want to copy the code everywhere. In our case we are using
transitions
as our workflow gem, so instead of having a flagapproved
we have a string columnstate
.A model that requires approval looks like this:
Then we have a workflow that looks like this:
So what's going on here is that we've created a module, which you can think of like an anonymous piece of code which does't belong anywhere (read more about modules to understand why this is an awful description), which we then include in our classes which mixes in the functionality. Now our comment class has the approval workflow!
In you case, assuming you were to keep the approval flag, you might add default validations, some methods like
approve!(user)
or scopes for querying.I hope this helps.
使用多态关联并不是解决方案,除非它们都是相同的基础对象。请记住,通过继承,父级应该与子级建立一种 is-a 关系。
您可以做的是创建一个
Approval
模型并与可批准的模型建立一对一的关系。Using polymorphic associations is not the solution unless they are all the same base object. Keep in mind that with inheritance the parent should have an is-a relationship with the child.
What you could do is create an
Approval
model and have a one-to-one relationship with the approvable models.