2015-08-08 35 views
0

我想弄清楚如何編寫一個查詢,我可以使用一個.where和一個變量,它包含一天的首選項,將查詢我的事件表的這些首選項的數組。Rails 4查詢。其中有一個數組變量

Event Model 
    belongs_to :event_type 
    has_many :sub_events, dependent: :destroy 

User Model 
    has_many :user_sub_events 
    has_many :sub_events, through: :user_sub_events 
    has_many :user_preferences 
    has_many :preferences, through: :user_preferences 

Preference Model 
    has_many :user_preferences 
    has_many :users, through: :user_preferences 
    belongs_to :preference_type 

class UserPreference < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :preference 
end 

這就是我試圖運行查詢的地方。在用戶控制器中。我有一個儀表板方法設置。

def dashboard 
    @preferences = current_user.preferences.where(preference_type_id: 1) 
    @suggested_tasks = Event.where(day: ['Monday', 'Friday']) 
end 

所以我得到,我可以查詢我的用戶的喜好,而preference_type_id:1是每日偏好。所以我抓住@preferences變量。然後在@suggested_tasks變量中,我想查詢@preferences變量中的內容。所以我需要用@preferences變量中的任何內容替換['Monday','Friday']數組。

如果我輸出的是在@preferences變量在我看來,我得到:

感謝您的答覆。是的,我將在@preferences變量中獲取用戶首選項。所以,如果我輸出@preferences在我看來,我得到

Monday 
Friday 
Tuesday 
Wednesday 

哪些是我選擇哪些用戶的喜好和存儲在通過表User_Preferences。

我想 '在' 子句在查詢中使用的,但我現在得到一個錯誤:

Mysql2::Error: Operand should contain 1 column(s): SELECT事件.* FROM事件WHERE (day in (SELECT喜好.* FROM喜好INNER JOIN user_preferences ON喜好. ID = user_preferences . preference_id WHERE user_preferences . user_id = 1 AND首選項. preference_type_id = 1))

我的查詢i s:

preferences = current_user.preferences.where(preference_type_id: 1) 
@suggested_tasks = Event.where("day in (?)", preferences) 
+0

此刻你在'@ preferences'中獲得多條記錄嗎?你可以輸出一些數據... – alexsmn

回答

0

好吧,我想通了。我不知道這是否是最好的方法,但這是我的新問題。這會從直通表中抓取當前用戶的偏好。然後它查詢映射到首選項名稱(這是當天的字符串值)的事件表。所以,基本上在用戶偏好表中,它存儲了一天的字符串。在Event表中,它存儲從使用strftime(%A)爲該對象創建的日期解析的日期的字符串值。

@preferences = current_user.preferences.where(preference_type_id: 1) 
@suggested_tasks = Event.where('day in (?)', @preferences.map {|x| x.name }) 
+1

你有沒有嘗試在@preferences的查詢中做一個.select(:name)?那麼你應該能夠擺脫地圖,一切都保持在主動記錄/數據庫中。 – srecnig

相關問題