2012-08-31 28 views
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行

任何人都可以请帮我这?

回答

0

UserShop

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

创建一个新的模型。然后对一些user你可以做

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

,你也可以直接从User

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

加关系UserShop和给一些user,你可以做

user_shops = user.user_shops 
+0

,但我使用has_and_belongs_to_many协会,负责管理在后台连接表,你告诉我再添模型之间。请问User.shops << some_shop_object会将对象添加到UserShop? –

+0

'UserShop'只是Rails中的一个接口,与数据库中已有的'user_shops'表相关。 User.shops << some_shop_object'的行为与此模型的存在没有区别。 – deefour

+0

模型的存在,目前您只能作为API用于查询'user_shops'表;而已。 – deefour