如何建立一对多的关系?

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)

  • 诚然 :).只是为了未来的读者,所以他们知道如何添加ID. (8认同)
  • 现在不应该用`add_reference`吗? (2认同)

kla*_*eck 7

根据您的数据库设置,您只需要在模型中添加以下行:

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回答.