【问题标题】:Rails association with models and migrationRails 与模型和迁移的关联
【发布时间】:2013-10-24 22:49:19
【问题描述】:

无法理解 Rails 与模型的关联是如何工作的。这是一个简单的问题:

有两个表

产品

id|   name  | status
1 | Tube    | 0
2 | Pillar  | 1
3 | Book    | 0
4 | Gum     | 1
5 | Tumbler | 2

状态

status | name
0      | Unavailable
1      | In stock
2      | Discounted

模型和控制器的名称相同。

我不会在每个新产品的状态表中创建新行。我想在 erb 中显示状态名称。我应该在模型和迁移文件中写什么(例如对于 which belongs_to、has_one 或 has_many...)?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 model ruby-on-rails-4


    【解决方案1】:

    对于简单的一对多关联,产品应该belongs_to :status 和状态应该has_many :products,并且您不需要为产品设置状态。在 erb 中,您将使用 <%= @product.status.name %>。要设置这些迁移,create_table :products do |t| t.string :name; t.integer :status_id; end 和 create_table :statuses do |t| t.string :name; end

    more information here

    【讨论】:

      【解决方案2】:

      首先,根据 Rails 约定,您需要将 product.status 重命名为 product.status_id。

      产品属于_to :status
      状态 has_many :products

      Product.find(1).status.name 应该是“不可用”

      【讨论】:

        【解决方案3】:

        如果您了解关系数据库的基础知识,那么这几乎是一回事。
        当您说 status belongs_to :product 和 product has_many :statuses 时,它本质上意味着状态表有一个外键,您可以使用它来检索给定产品 ID 的所有状态行。

        要建立这种关系,您需要在状态表中创建一个新列 product_id:

        rails g migration AddProductIdToStatuses product_id:integer
        

        完成后,在您的 product.rb 中添加以下内容:

        has_many :statuses
        

        这在你的 status.rb 中:

        belongs_to :product
        

        【讨论】:

        猜你喜欢
        • 2021-07-06
        • 1970-01-01
        • 1970-01-01
        • 2017-03-15
        • 2013-04-29
        • 2017-10-26
        • 2015-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多