![](/img/trans.png)
[英]Rails 5: Add belongs_to association with custom name to model, and migration
[英]How to write a migration for a rails model that belongs_to itself
模型場景:
A node can belong to a parent node and can have child nodes.
車型/ node.rb
class Node < ActiveRecord::Base
has_many :children, class_name: "Node", foreign_key: "parent_id"
belongs_to :parent, class_name: "Node"
end
分貝/遷移/ 20131031144907_create_nodes.rb
class CreateNodes < ActiveRecord::Migration
def change
create_table :nodes do |t|
t.timestamps
end
end
end
然后我想做遷移添加關系:
class AddNodesToNodes < ActiveRecord::Migration
def change
add_column :nodes, :parent_id, :integer
# how do i add childen?
end
end
如何在遷移中添加has_many關系?
您已經完成了所需的一切。您可以在此頁面中找到更多信息:
資料來源: http : //guides.rubyonrails.org/association_basics.html
node.parent
將查找parent_id
是節點id並返回父節點。
node.children
將發現parent_id
是節點id並返回子節點。
當你添加關系時,你可以在Rails 4中這樣做:
## rails g migration AddNodesToNodes parent:belongs_to
class AddNodesToNodes < ActiveRecord::Migration
def change
add_reference :nodes, :parent, index: true
end
end
Per RailsGuides ,這是一個自我加入的例子。
# model
class Node < ActiveRecord::Base
has_many :children, class_name: "Node", foreign_key: "parent_id"
belongs_to :parent, class_name: "Node"
end
# migration
class CreateNodes < ActiveRecord::Migration
def change
create_table :nodes do |t|
t.references :parent, index: true
t.timestamps null: false
end
end
end
遷移中不需要任何其他內容。 parent_id用於定義兩個方向的關系。 特別:
parent - 具有與當前節點的parent_id屬性值對應的id的節點。
children - 具有parent_id值的所有節點,該值對應於當前節點的id屬性的值。
您已經使用AddNodeToNodes和父ID編寫了遷移。
這在數據庫級別定義它。
在'rails'級別(ActiveRecord),您可以在模型定義中定義has_many,即定義Node類的Node.rb文件。
添加has_many沒有“遷移”。 遷移用於數據庫字段(和索引等),例如parent_id
但不用於rails樣式關系定義,例如has_many
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.