2013-05-07 25 views
0

我使用的設計進行驗證,並感到我的用戶與他們可以在登錄子域相關聯的方式難倒可以登錄下多個子域。我研究了plataformatec提供的信息here以及Dave Kenedy在Ruby Source here上的傑出文章。儘管如此,我仍然不完全理解聯合和查詢的好處。合併在軌3.2多個模型,以便用戶使用設計

class User < ActiveRecord::Base 
    has_many :residences 
    ... 
end 

class Residence < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :apartment 
    ... 
end 

class Apartment < ActiveRecord::Base 
    has_many :residences 
    belongs_to :building 
    ... 
end 

class Building < ActiveRecord::Base 
    attr_accessible :subdomain 
    has_many :apartments 
    ... 
end 

config/initializers/devise.rb我說:

config.request_keys = [:subdomain] 

app/models/user.rb我把它換成默認色器件的方法,`self.find_for_authentication有:

def self.find_for_authentication(conditions={}) 
    conditions[:residences] = { :subdomain => conditions.delete(:subdomain) } 
    find(:first, :conditions => conditions, :joins => :residences) 
end 

當我跑我的規格我得到以下錯誤:

PG::Error: ERROR: column residences.subdomain does not exist 

我知道,不知怎的,我有我的residence表連接一路到building表來確認用戶登錄隸屬於用正確的子域的建築物,但我不知道該怎麼做。有人有主意嗎? Rails Docs有關於連接表的信息,但也讓我感到困惑。 (對數據庫的基本信息和連接表也將會有所幫助。;-))

更新

我在app /模型/ user.rb已經修訂

def self.find_for_authentication(conditions={}) 
    subdomain = conditions.delete(:subdomain) 
    building = Building.find_by_subdomain(subdomain) 
    apartments = Apartment.where('apartment.building_id' => building.id) 
    conditions[:residences] = { :apartment_id => apartments } 
    find(:first, :conditions => conditions, :joins => :residences) 
end 

這可能是有點接近我所需要的,但我還是發現了以下錯誤在rspec的:

1) UserSubdomainLogins signin should not be able to signin to building without access 
Failure/Error: click_button "Sign in" 
ActiveRecord::StatementInvalid: 
    PG::Error: ERROR: missing FROM-clause entry for table "apartment" 
    LINE 1: ...SELECT "apartments"."id" FROM "apartments" WHERE "apartment... 
                   ^
    : SELECT "users".* FROM "users" INNER JOIN "residences" ON "residences"."user_id" = "users"."id" WHERE "users"."email" = '[email protected]' AND "residences"."apartment_id" IN (SELECT "apartments"."id" FROM "apartments" WHERE "apartment"."building_id" = 2895) ORDER BY last_name ASC LIMIT 1 
+0

哪個模型有子域場? – 2013-05-08 14:29:54

+0

對不起,@ShawnBalestracci,我應該更加明確。建築物具有子域屬性。 – BenU 2013-05-08 15:34:37

回答

1

在你修改您需要更改的公寓公寓:

apartments = Apartment.where('apartments.building_id' => building.id) 

下面介紹如何使用做聯接:下列指南中

#subdomain is already in the conditions so you don't need to do anything 
def self.find_for_authentication(conditions={}) 
    find(:first, :conditions => conditions, 
    :joins => {:residences => {:apartment => :building }}) 
end 

參見11.2.4節有關嵌套使用哈希聯接的更多信息。 http://guides.rubyonrails.org/active_record_querying.html#joining-tables

+0

謝謝@ShawnBalestracci。這個答案可能適用,但我認爲我已經得到了Devise的一些問題,我必須解決它。我希望在接下來的幾天內做到這一點,並報告回來。 – BenU 2013-05-08 20:55:58