這聽起來有點複雜,但實際上不應該如此。我正在使用Rails作爲API,並且有一個接受項目數組的端點。我想返回所有屬於它的記錄匹配數組中至少一個元素的記錄。Ruby on Rails - 返回子記錄與數組中元素匹配的所有記錄
例如,假設我正在創建博客,並且有帖子和標籤。
我可能要求是這樣的:
GET http://localhost:3000/api/v1/posts_by_tag?tags=news,weather,life
然後在routes.rb中
get '/posts_by_tag' => 'posts#index_by_tag'
和posts_controller.rb
def index_by_tag
tags = params[:tags].split(',')
@posts = Post.where(any element in Post.tags matches any element in tags)
render json: @posts.to_json, status: :ok
end
在假設的例子以上, 一世想要返回所有包含「新聞」,「天氣」或「生活」標籤的帖子。
我來自節點,最近沒有花費太多時間在Rails上。但是這種感覺就像是有一種非常明確的Rails/ActiveRecord方法來實現這一點。
它是一種什麼樣的數組?你使用的是哪個數據庫? – ollpu
我使用的是Postgres,而數組就是Ruby的String.split()方法生成的任何類型的數組。 – jmknoll
但是什麼類型的數組是post.tags?它是一個Postgres數組嗎? – ollpu