(MVC) 跨越多个模型的逻辑

发布于 2024-10-19 16:34:59 字数 323 浏览 3 评论 0原文

我的设置:Rails 2.3.10、Ruby 1.8.7

我想要一些关于逻辑代码和 REST API 最好放在哪里的反馈,这些代码在单个事务中涉及多个模型。例如,用户需要购买产品,这会涉及到

  1. 检查他是否有足够的钱(用户模型)
  2. 检查产品是否可用(产品型号)
  3. 计算运费(邮政编码,产品型号)
  4. 减去金钱
  5. 更新产品可用数量
  6. ...

你就明白了。假设我需要提供一个购买 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

  1. Checks if he has sufficient money (user model)
  2. Check if the product is available (product model)
  3. Calculate shipping charge (zipcode, product models)
  4. Subtract money
  5. Update product availability count
  6. ...

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城泪 2024-10-26 16:34:59

我不知道约定是什么(如果有的话),但我倾向于以“名词-动词”格式进行多模型交易。例如,如果用户想要购买产品,我会这样做:

class User < ActiveRecord::Base
  ...
  def purchase(product)
    product.logic
    self.step_3_profit
    etc
  end
end

控制器的工作原理类似,尽管我通常用被动语态思考它(例如,“什么动词正在对什么名词进行”,而不是“什么名词正在做什么动词”。例如,如果购买了产品,则它可能是POST/products/1/purchase,使用以下控制器代码:

class ProductsController < ApplicationController
  include SessionsHelper

  def purchase
    current_user.purchase Product.find(params[:id])
    do_view_stuff
  end
end

使用这些“约定”,我可以通过思考正在执行什么动词来轻松找到应用程序中的逻辑什么名词。

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 a Product, I would do:

class User < ActiveRecord::Base
  ...
  def purchase(product)
    product.logic
    self.step_3_profit
    etc
  end
end

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 a POST to /products/1/purchase, with the following controller code:

class ProductsController < ApplicationController
  include SessionsHelper

  def purchase
    current_user.purchase Product.find(params[:id])
    do_view_stuff
  end
end

Using these "conventions", I can easily locate the logic in my app by thinking about what verb is being done to what noun.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文