【问题标题】:ruby on rails can't create physical relationships with modelsruby on rails 无法与模型建立物理关系
【发布时间】:2019-09-02 16:10:38
【问题描述】:

我不确定为什么我没有一对多关系的物理外键。订单有很多评论。与其他关系相同。

型号:

class Order < ApplicationRecord
    has_many :invoices
    has_many :payments through => :invoices
    belongs_to :user
    has_many :comments
    has_many :options
    has_many :media through => :options
    has_many :auctions
    has_many :factmails
    belongs_to :orderstatus

end


class Comment < ApplicationRecord
    belongs_to :order

end

迁移:

class CreateComments < ActiveRecord::Migration[5.2]
  def change
    create_table :comments do |t|
      t.text :content
      t.belongs_to :order, index: true
      t.timestamps
    end
  end
end

DDL:

CREATE TABLE public.comments (
    id int8 NOT NULL DEFAULT nextval('comments_id_seq'::regclass),
    content text NULL,
    created_at timestamp NOT NULL,
    updated_at timestamp NOT NULL,
    PRIMARY KEY (id)
)
WITH (
    OIDS=FALSE
) ;

我做错了什么?当您首先定义模型然后想在它们之间创建关系时,正确的策略是什么?

【问题讨论】:

  • 应该是:through =&gt; ...(旧样式)或through: ...(当前样式)。
  • 在迁移中没有得到order_id 列似乎很奇怪。
  • 这就是我问的原因..它之后没有出现
  • 会不会是:order这个名字有问题?

标签: ruby-on-rails ruby postgresql activerecord model


【解决方案1】:

你确定没有修改迁移文件添加行

t.belongs_to :order, index: true

运行命令后rails db: migrate 如果是这样,您需要回滚迁移并重新执行它们

【讨论】:

  • :order 是一个符号。 order 是一个未定义的变量。
猜你喜欢
  • 1970-01-01
  • 2018-04-05
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多