I
I
Ilnar252016-07-08 11:38:16
Ruby on Rails
Ilnar25, 2016-07-08 11:38:16

How to get posts by tags?

I have 2 models connected via a third has_many :through
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "body"
end
create_table "tags", force: :cascade do |t|
t.string "name"
end
create_table "tags_associations", force: :cascade do |t|
t.integer "post_id"
t.integer "tag_id"
end
How should a request to get all posts for a specific tag look like when receiving such a param. Parameters: {"tag"=>"3"}.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilnar25, 2016-07-08
@Ilnar25

@posts = Post.posts_for_tag(params[:tag])
scope :posts_for_tag, -> (tag) do
includes(:tags_associations, :tags)
.joins(:tags)
.where("tags_associations.tag_id = ?", tag )
end
decided himself right or wrong, but it seems to work)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question