2016-08-31 34 views
0

這聽起來有點複雜,但實際上不應該如此。我正在使用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方法來實現這一點。

+0

它是一種什麼樣的數組?你使用的是哪個數據庫? – ollpu

+0

我使用的是Postgres,而數組就是Ruby的String.split()方法生成的任何類型的數組。 – jmknoll

+0

但是什麼類型的數組是post.tags?它是一個Postgres數組嗎? – ollpu

回答

3

我假設你有一個模型Tag,這是由命名,比如說PostTagging模型,加盟Post

class PostTagging < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :tag 
end 

class Post < ActiveRecord::Base 
    has_many :post_taggings 
    has_many :tags, through: :post_taggings 
end 

因此,讓所有的帖子與標籤所有你需要做的是加入TagPost並搜索Tag型號:

Post.joins(:tags).where(tags: { name: tags })

你被允許做joins(:tags)因爲你在Posttags裏面指定了一個關係where是一個標籤名稱數組。十分簡單!

+0

根據OP,沒有中間模型,它是一個直接'has_many'關聯。另外,如果您的示例在tags-array中有多個匹配的標籤,它將多次返回相同的帖子。 '.distinct'應該照顧這個。 – ollpu

+0

我找不到OP狀態,他沒有中間模型,但是如果他不那麼pankaj答案會工作得很好:) – shlajin

+0

不,pankaj的答案只能檢查帖子的單個「標籤」屬性。 – ollpu

0
Post.where(tags: tags) => 
    SELECT `posts`.* 
    FROM `posts` 
    WHERE `posts`.`tags` 
    IN ('News', 'Weather', 'Life') 
相關問題