A Post
has_many Tags
. Each tag record has a name, like "fashion" or "business".
How can I get all posts that have the tag with name "fashion"?
# Get all posts
@posts = Post.all
# Get the filter tag
@filter_tag = Tag.find_by_name(params[:filter_name])
Ok so now we have all posts, and now I just want the @posts that have the @filter_tag. What should I do?
I could loop through each post, and check if it has the filter tag. If so, add it to an array. I'm sure Rails ActiveRecord has a better method though.
如果您的关联设置正确,则
@filter_tag_posts = @filter_tag.posts
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.