【问题标题】:What Rails-ActiveRecord association to use for this?为此使用什么 Rails-ActiveRecord 关联?
【发布时间】:2016-08-07 08:00:17
【问题描述】:

假设我有一个计算机模型。

这台电脑有两个特点:

  • 一个名字。

  • 价格。

这些特征如何与计算机模型相关联? (例如:belongs_to、has_one、yadda yadda)

【问题讨论】:

  • 普通属性只是 db 列,不需要关联。或澄清您的问题
  • 您不需要关联,只要nameprice 是字符串或整数等简单属性。当您有单独的模型时需要关联,例如 Price 模型并希望将它们链接在一起

标签: ruby-on-rails ruby activerecord associations


【解决方案1】:

我会这样设置计算机模型:

> bundle exec rails g model computer name:string price:integer

# app/models/computer.rb
class Computer < ApplicationRecord
end

# db/migrate/20160807225007_create_computers.rb 
class CreateComputers < ActiveRecord::Migration[5.0]
  def change
    create_table :computers do |t|
      t.string :name
      t.integer :price

      t.timestamps
    end
  end
end

如果两个属性都是原始类型,则不需要关联。

【讨论】:

    【解决方案2】:

    如果你的名字和价格是一个模型而不是把它们与计算机之间的关联做起来就好了 电脑型号

    has_many :name has_many :价格

    有很多并属于关联取决于您希望如何与他们建立关联

    例如,如果您希望计算机型号的名称与 has_many :name 不同,并且您希望您的计算机型号应该是名称型号而不是 do 属于_to :name

    查看此链接了解更多详情:http://guides.rubyonrails.org/association_basics.html

    【讨论】:

    • 我无法理解 ROR 指南。不过我理解你。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    相关资源
    最近更新 更多