Mysql Rails关联和删除
我正在通过Rails协会。但我无法理解该协会是如何运作的。我正在使用mysql数据库 以下是我生成的文件: user.rbMysql Rails关联和删除,mysql,ruby-on-rails,associations,Mysql,Ruby On Rails,Associations,我正在通过Rails协会。但我无法理解该协会是如何运作的。我正在使用mysql数据库 以下是我生成的文件: user.rb class User < ActiveRecord::Base has_many :orders end class Order < ActiveRecord::Base belongs_to :user end class CreateOrders < ActiveRecord::Migration def change
class User < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :user
end
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.string :content
t.integer :user_id
t.timestamps null: false
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps null: false
end
end
end
class用户
订单.rb
class User < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :user
end
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.string :content
t.integer :user_id
t.timestamps null: false
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps null: false
end
end
end
类顺序
20150911181301创建订单。rb
class User < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :user
end
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.string :content
t.integer :user_id
t.timestamps null: false
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps null: false
end
end
end
class CreateOrders
20150911181351\u创建用户。rb
class User < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :user
end
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.string :content
t.integer :user_id
t.timestamps null: false
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps null: false
end
end
end
class CreateUsers
首先,我希望db:migrate本身会生成一些外键关系,但它没有发生。然后我想可能是rails在内部管理它,但是当我通过rails c
删除一个用户时,它没有从订单表中删除相应的订单
我的理解哪里不正确?也给我一些链接,解释这是如何工作的 这是有争议的,但传统的“Rails方式”是在ActiveRecord级别而不是在数据库中管理与模型相关的东西,如默认值、外键和触发器 也就是说,您可以使用以下方法在迁移中自由添加外键以实现引用完整性:
add_foreign_key :orders, :users
有关更多信息,请参阅
销毁父对象时自动销毁子对象的“Rails方法”是指定子集合上的
:dependent
策略。关于这两个:dependent
选项有一个非常详细的Stackoverflow讨论::destroy
vs:delete\u all
所有内容都在文档中
-您应该注意,“在任何情况下,Rails都不会为您创建外键列。。您需要在迁移过程中明确定义它们。”
-您还应该注意,当涉及到关联时,Rails需要您告诉它,由于与相关的两个模型属于,并且有许多,因此您希望在删除其父模型时删除关联模型。这就是dependent::destroy
的作用
现在,您需要在代码中为与用户相关的订单
执行的所有操作都将在以下情况下被删除:
class User < ActiveRecord::Base
has_many :orders, dependent: :destroy
end
class用户
资料来源: