使用关系数据库

时间:2014-10-29 14:57:04

标签: ruby-on-rails postgresql relational-database

我有三个表Business,Users和Subscriptions。目标是能够获得业务'与用户关联的名称。结果应该是用户在订阅中注册的商业名称数组

表格列表

Schema |       Name        | Type  |
--------+-------------------+-------
 public | businesses        | table 
 public | subscriptions     | table 
 public | users             | table

企业表

  Column   |            Type                                                        
------------+-----------------------------
 id         | integer                      
 name       | character varying(255)       
 created_at | timestamp without time zone  
 updated_at | timestamp without time zone  

商业模式

class Business < ActiveRecord::Base

end

订阅表

   Column    |            Type                                   
-------------+-----------------------------
 id          | integer                     
 user_id     | integer                      
 business_id | integer                      
 created_at  | timestamp without time zone  
 updated_at  | timestamp without time zone

订阅模式

class Subscription < ActiveRecord::Base
   belongs_to :user
   belongs_to :business
end

用户表

     Column      |            Type                                   
-----------------+-----------------------------
 id              | integer                 
 username        | character varying(255)       
 password_digest | character varying(255)       
 email           | character varying(255)       
 created_at      | timestamp without time zone  
 updated_at      | timestamp without time zone 

用户模型

 class User < ActiveRecord::Base
       has_secure_password
       has_many :subscriptions
    end

Rails控制台

 u = User.find(1)
 u.subscriptions.businesses.name

 Response: undefined method `business'

2 个答案:

答案 0 :(得分:1)

由于用户有许多订阅,因此对u.subscriptions的调用会返回一个订阅数组,因此您需要遍历该数组并在每条记录上调用business关联。您可以使用以下方式实现所需:

business_names = u.subscriptions.map {|subscription| subscription.business.name }

答案 1 :(得分:1)

您可以使用Rails&#39;进行一次查询,而不是对每个订阅进行额外的查询(如在Alireza的答案中)。内置includes方法:

subscriptions = u.subscriptions.includes(:business)

这将返回所有订阅的关系,包括其关联的业务。现在你可以获得业务&#39;没有进行额外查询的名称:

business_names = subscriptions.map {|sub| sub.business.name }

认为您也可以使用pluck一步完成此操作:

business_names = u.subscriptions.includes(:business).pluck("businesses.name")

我不确定pluckincludes的搭配是否合适,但值得一试。