1
我想通過Rails查詢界面運行下面的查詢,但無法翻譯我的邏輯。查詢是添加「和」和「或」子句通過rails查詢界面查詢
Select f.* from feeds f
Left join feed_items fi on fi.id = f.feedable_id
where
f.feedable_type in ('Homework', 'Datesheet')
and
(
(fi.assignable_type = 'Level' and assignable_id IN (1)) or
(fi.assignable_type = 'Student' and assignable_id IN (1)) or
(fi.assignable_type = 'Section' and assignable_id IN (1))
)
場景:
我收到以下PARAMS散列包含將動態在我的查詢
{"page"=>"1", "limit"=>"2", "type_filter"=>["Homework", "Datesheet"], "assignable_filter"=>{"Student"=>"[2]", "Section"=>"[1]", "Level"=>"[1]"}}
到目前爲止,加入過濾器,我的動作我做了什麼正在加入表格並添加where子句的類型過濾器,但不知道如何動態添加assignable_filters。這裏是我的Rails代碼,options
是params
在下面的代碼
def get_feeds(options)
base = Feed.includes(:feed_item)
base = add_type_filters base, options
base = add_assignable_filters base, options
format_response base, options
end
def add_type_filters(base, options)
type_filter = options[:type_filter]
if !type_filter.nil? and type_filter.length > 0
base = base.where('feedable_type IN (?)', options[:type_filter])
end
base
end
def add_assignable_filters(base, options)
assignable_filter = options[:assignable_filter]
if !assignable_filter.nil?
assignable_filter.each do |key, value|
# code for adding filters combined with or conditions
end
# wrap the or conditions and join them with an and in main where clause
end
base
end
P.S我用導軌5
我注意到的第一件事:是不是feed和feed_items(一對多關係?)。如果是'Feed.includes(:feed_items)'是正確的。 – haffla
在這裏您可以看到如何在Rails5中執行OR查詢:https://stackoverflow.com/questions/32753168/rails-5-activerecord-or-query – haffla
@haffla其一對一關聯 –