【发布时间】:2016-01-11 13:50:19
【问题描述】:
我正在尝试从使用 sqlite3 gem 的直接查询转移到 Active Record。
以下是 Active Record 设置:
ActiveRecord::Schema.define do
unless ActiveRecord::Base.connection.tables.include? 'admins'
create_table :admins do |table|
table.column :network_id, :integer
table.column :text, :string
end
end
unless ActiveRecord::Base.connection.tables.include? 'channels'
create_table :channels do |table|
table.column :network_id, :integer
table.column :name, :string
table.column :users, :integer
table.column :topic, :string
end
end
unless ActiveRecord::Base.connection.tables.include? 'messages'
create_table :messages do |table|
table.column :network_id, :integer
table.column :text, :string
end
end
unless ActiveRecord::Base.connection.tables.include? 'networks'
create_table :networks do |table|
table.column :name, :string
end
end
unless ActiveRecord::Base.connection.tables.include? 'servers'
create_table :servers do |table|
table.column :network_id, :integer
table.column :ip, :string
table.column :port, :integer
end
end
unless ActiveRecord::Base.connection.tables.include? 'users'
create_table :users do |table|
table.column :network_id, :integer
table.column :global, :integer
table.column :global_max, :integer
table.column :local, :string
table.column :local_max, :integer
end
end
end
class Admin < ActiveRecord::Base
belongs_to :network
end
class Channel < ActiveRecord::Base
belongs_to :network
end
class Messages < ActiveRecord::Base
belongs_to :network
end
class Network < ActiveRecord::Base
end
class Server < ActiveRecord::Base
belongs_to :network
end
class User < ActiveRecord::Base
belongs_to :network
end
由于我已将belongs_to 添加到每个类,因此数据库查询不会保存到数据库中,但没有显示错误消息,这让我相信我可能误解了如何使用这些belongs_to 等。
基本上所有其他表都有一个network_id 列需要映射到networks 表的id 列,所以如果有人试图用network_id 插入到admins 表中1 但 1 在 networks 表中不存在它应该失败。
我应该在这里使用belongs_to 吗?
我还应该使用has_one、has_many 等其他名称吗?我习惯于编写简单的 SQL 查询,因此阅读和尝试理解 Active Record 文档有点令人困惑!
【问题讨论】:
标签: ruby activerecord