【发布时间】:2011-12-18 21:49:14
【问题描述】:
我有以下型号:
User (id, name, network_id)
Network(id, title)
我需要添加什么样的 Rails 模型关联才能做到:
@user.network.title
@network.users
谢谢
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord activemodel
我有以下型号:
User (id, name, network_id)
Network(id, title)
我需要添加什么样的 Rails 模型关联才能做到:
@user.network.title
@network.users
谢谢
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord activemodel
so 网络 has_many 用户和用户 belongs_to 网络。
如果您还没有添加 network_id 到 users 表,并且因为它是一个 foreign_key 值得索引它。
rails generate migration AddNetworkIdToUsers
class AddNetworkIdToUsers < ActiveRecord::Migration
def change
add_column :users, :network_id, :integer
add_index :users, :network_id
end
end
在网络模型中做:
class Network < ActiveRecord::Base
has_many :users
end
在用户模型中做:
class User < ActiveRecord::Base
belongs_to :network
end
【讨论】:
add_reference吗?
根据您的数据库设置,您只需将以下几行添加到您的模型中:
class User < ActiveRecord::Base
belongs_to :network
# Rest of your code here
end
class Network < ActiveRecord::Base
has_many :users
# Rest of your code here
end
如果您的设置没有 network_id,您应该使用 daniels answer。
【讨论】:
这是我的方式: 运行:
$rails generate migration AddNetworkIdToUsers
然后配置迁移文件:
class AddNetworkIdToUsers < ActiveRecord::Migration[5.1]
def up
add_column :users, :network_id, :integer
add_index :users, :network_id
end
def down
remove_index :users, :network_id
remove_column :users, :network_id
end
end
【讨论】: