【问题标题】:How to Connect models in Ruby on Rails如何在 Ruby on Rails 中连接模型
【发布时间】:2020-06-03 03:23:43
【问题描述】:

我是 Ruby on Rails 的新手,我正在尝试构建一个简单的商店应用程序,为用户提供以下 2 个基本商店选项:

添加客户(姓名、从商店购买的产品和首选付款方式(只能设置为“现金”或“信用卡”)。

将产品添加到商店(名称、价格和购买此产品的所有客户)

我知道has_many 和belongs_to,但在这种情况下,两者都有很多。 我考虑过为他们两个都使用 $ 'rails g scaffold',但是根据您的经验,在客户和产品之间建立联系的最佳方式应该是什么?

如何在新客户表单中将“现金”/“信用”选项呈现为简单的下拉菜单?

【问题讨论】:

标签: ruby-on-rails ruby sqlite


【解决方案1】:

基于Many-to-Many数据模型,你应该创建关系表(连接表)。

如果模型之间的关系应该有额外的字段或额外的代码 - 你应该使用has_many :through association

否则 - 您可以使用has_and_belongs_to_many association

【讨论】:

    【解决方案2】:

    您可以生成一个新模型,将客户与其购买的产品联系起来

    rails g model cutomer_products customer:references product:references payment_method:{string or references if you has a payment method table}
    

    确保 cutomer_product 模型是这样的:

    class CutomerProduct < ApplicationRecord
      has_many :products
      has_many :customers
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2020-04-23
      相关资源
      最近更新 更多