0

我有两个模型

 class User < ActiveRecord::Base
  has_and_belongs_to_many :shops
 end

 class Shop < ActiveRecord::Base
  has_and_belongs_to_many :users
 end

我必须从与用户对象关联的连接表 users_shops 中找到行

谁能帮我解决这个问题?

4

1 回答 1

0

UserShop

class UserShop < ActiveRecord::Base
  belongs_to :user
  belongs_to :shop
end

然后对于一些user你可以做

user_shops = UserShop.where(:user_id => user.id)

您也可以直接将关系添加到UserShopfromUser

class User < ActiveRecord::Base
  has_and_belongs_to_many :shops
  has_many :user_shops
end

给定一些user,你可以做

user_shops = user.user_shops
于 2012-08-31T12:18:08.817 回答