Skip to main content
Version: v3.0

Search, attachments and tags

This tutorial will walk you through extending the Tutorial to add more advanced features:

  • Search
  • File Attachments
  • Tags

Prerequisites

Ensure you have completed the Tutorial.

Data model

The following data model will be used for this tutorial.

Every blog has a category and a series of blog posts. Each blog has a banner image. Each blog post can have 1 or more tags.

info

The user, tags and file attachment models are provided by Rails & Rhino.

Add search to the Blog model so that the user can search for blogs by title with rhino_search.

app/models/blog.rb
class Blog < ApplicationRecord
belongs_to :user
belongs_to :category
has_many :blog_posts, dependent: :destroy

# Rhino specific code
rhino_owner_base
rhino_references [:user, :category]
rhino_search [:title]

validates :title, presence: true
end

You will now have a search box in the UI to search for blogs by title if you refresh the browser.

File Attachments

Add file to display a banner image for the blog.

app/models/blog.rb
class Blog < ApplicationRecord
belongs_to :user
belongs_to :category
has_many :blog_posts, dependent: :destroy

has_one_attached :banner

# Rhino specific code
rhino_owner_base
rhino_references [:user, :category, :banner_attachment]
rhino_search [:title]

validates :title, presence: true
end
warning

You must include the :banner_attachment in the rhino_references array to make the file available through the Blog API call.

info

has_one_attached is from a feature of Rails called ActiveStorage that manages file attachments.

You will now be able to upload a file when creating or editing a blog.

Tags

Add tagging to the BlogPost model so that the user can add tags to blog posts. Install the tagging migrations:

docker compose run --rm backend "rails acts_as_taggable_on_engine:install:migrations"
docker compose run --rm backend "rails db:migrate"

And add tagging to the BlogPost model.

app/models/blog_post.rb
class BlogPost < ApplicationRecord
belongs_to :blog

acts_as_taggable_on :tags

# Rhino specific code
rhino_owner :blog
rhino_references [:blog]

validates :title, presence: true
validates :body, presence: true
end
info

acts_as_taggable_on :tags is from the acts-as-taggable-on gem that manages tags for ActiveRecord objects.

You will now be able to add one or more tags to a blog post.