0
我有以下型号:List
有(名称和user_id字段)和User
。如何使用连接表在Rails中创建has_many和belongs_to关联?
每个列表都有很多用户。并且每个列表都属于一个用户。
我创建client_lists
表:
class CreateClientListsTable < ActiveRecord::Migration
def change
create_table :client_lists do |t|
t.integer :user_id
t.integer :list_id
end
add_index :client_lists, :user_id
add_index :client_lists, :list_id
end
end
现在的第一个关系很容易地说,名单属于用户,并且用户有许多名单:
class List < ActiveRecord::Base
belongs_to :user
validates :user, :presence => true
end
而且
class User < ActiveRecord::Base
has_many :lists, :dependent => :destroy
end
无论如何,我该如何找到客户端列表client_lists表?
我添加列表HABTM关系
class List < ActiveRecord::Base
has_and_belongs_to_many :clients, :join_table => "client_lists", :foreign_key => "user_id"
end
然后试图List.first.clients
并得到了以下错误:
NameError: uninitialized constant List::Client