AnA*_*ice 22 activerecord ruby-on-rails activemodel ruby-on-rails-3
我有以下型号:
User (id, name, network_id)
Network(id, title)
Run Code Online (Sandbox Code Playgroud)
我需要添加什么样的Rails模型关联才能执行以下操作:
@user.network.title
@network.users
Run Code Online (Sandbox Code Playgroud)
谢谢
dan*_*iel 50
所以网络has_many用户和用户belongs_to网络.
network_id如果你还没有,那么只需添加一个到用户表,因为它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
Run Code Online (Sandbox Code Playgroud)
在网络模型中做:
class Network < ActiveRecord::Base
has_many :users
end
Run Code Online (Sandbox Code Playgroud)
在用户模型中执行:
class User < ActiveRecord::Base
belongs_to :network
end
Run Code Online (Sandbox Code Playgroud)
根据您的数据库设置,您只需要在模型中添加以下行:
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
Run Code Online (Sandbox Code Playgroud)
如果你有没有network_id的设置,你应该去daniels回答.
| 归档时间: |
|
| 查看次数: |
23585 次 |
| 最近记录: |