(MVC) 跨越多个模型的逻辑
我的设置:Rails 2.3.10、Ruby 1.8.7
我想要一些关于逻辑代码和 REST API 最好放在哪里的反馈,这些代码在单个事务中涉及多个模型。例如,用户需要购买产品,这会涉及到
- 检查他是否有足够的钱(用户模型)
- 检查产品是否可用(产品型号)
- 计算运费(邮政编码,产品型号)
- 减去金钱
- 更新产品可用数量
- ...
你就明白了。假设我需要提供一个购买 REST API,它应该进入哪个控制器?实际的逻辑应该去哪里?它应该在与控制器关联的模型中吗?感谢任何见解。
My setup: Rails 2.3.10, Ruby 1.8.7
I would like some feedback on where it is best to put logic code, and REST API, that touches multiple models in a single transaction. For example, a user needs to buy a product, it'll involve
- Checks if he has sufficient money (user model)
- Check if the product is available (product model)
- Calculate shipping charge (zipcode, product models)
- Subtract money
- Update product availability count
- ...
You get the general idea. Let's say I need to provide a buy REST API, which controller should it go in? And where should the actual logic go? Should it be in the model associated with the controller? Appreciate any insights.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道约定是什么(如果有的话),但我倾向于以“名词-动词”格式进行多模型交易。例如,如果
用户
想要购买产品
,我会这样做:控制器的工作原理类似,尽管我通常用被动语态思考它(例如,“什么动词正在对什么名词进行”,而不是“什么名词正在做什么动词”。例如,如果购买了
产品
,则它可能是POST
到/products/1/purchase
,使用以下控制器代码:使用这些“约定”,我可以通过思考正在执行什么动词来轻松找到应用程序中的逻辑什么名词。
I don't know what the convention is (if there is one), but I tend to do my multi-model transactions in a "noun-verb" format. For example, if a
User
wanted to purchase aProduct
, I would do:The controller works similarly, although I usually think about it in passive voice (e.g., "what verb is being done to what noun", rather than "what noun is doing what verb". For example, if a
Product
was being purchased, it might be aPOST
to/products/1/purchase
, with the following controller code:Using these "conventions", I can easily locate the logic in my app by thinking about what verb is being done to what noun.