我想弄清楚如何編寫一個查詢,我可以使用一個.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)
此刻你在'@ preferences'中獲得多條記錄嗎?你可以輸出一些數據... – alexsmn