简体   繁体   English

如何重命名外键?

[英]how to rename a foreign key?

I want to remove the _id prefix the foreign key? 我要删除_id前缀外键吗?
New table. 新表。 Two models Order and Product 两种型号OrderProduct

class Order < ApplicationRecord
  has_many :products
end
class Product < ApplicationRecord
  belongs_to :delivery, :class_name => "Order"
end

Make in the products table t.integer :delivery, index: true productst.integer :delivery, index: true

Error: 错误:

ActiveRecord::AssociationTypeMismatch: Order(#85313090) expected, got 1 which is an instance of Fixnum(#73138750)

How to fix? 怎么修?

To minimize the possibilities of fighting with rails when doing something like this, I'd simply override the delivery=(value) method. 为了最大程度地减少在执行此类操作时与rails冲突的可能性,我将简单地覆盖delivery=(value)方法。 eg: 例如:

class Product < ApplicationRecord
  belongs_to :delivery, :class_name => "Order"

  def delivery=(id)
    delivery_id = id
  end
end

In effect, this will prevent assigning objects to the association. 实际上,这将防止将对象分配给关联。 Other methods, eg build_delivery and delivery will still be present and could be overwritten as well but as @moveson has already pointed out, striving from the rails way will typically cause pain later on. 其他方法,例如build_deliverydelivery仍将存在,并且可能会被覆盖,但是正如@moveson已经指出的那样,从rails方式中进行尝试通常会在以后引起痛苦。

You need to specify foreign_key name in models: 您需要在模型中指定foreign_key名称:

class Order < ApplicationRecord
  has_many :products, foreign_key: "delivery"
end

class Product < ApplicationRecord
  belongs_to :delivery, :class_name => "Order", foreign_key: "delivery"
end

The good answer is you don't. 好的答案是你不会。 You can alias associations by using the foreign key and class_name options: 您可以使用外键和class_name选项对关联进行别名:

class Order < ApplicationRecord
  has_many :products, foreign_key: "delivery_id"
end

class Product < ApplicationRecord
  belongs_to :delivery, class_name: "Order"
end

But the _id suffix is a really good convention as it makes very easy to understand the schema as its almost overly apparent which columns are foreign key columns. 但是_id后缀是一个非常好的约定,因为它非常容易理解模式,因为它几乎是显而易见的,哪些列是外键列。 And conventions are what makes Rails awesome. 约定是使Rails很棒的原因。

There is no good reason to skirt it unless you have a crappy legacy application. 除非您拥有笨拙的旧版应用程序,否则没有充分的理由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM