Skip to content

Commit

Permalink
Merge pull request #8 from nashikotokyo/feature/07_search
Browse files Browse the repository at this point in the history
Feature/07 search
  • Loading branch information
nashikotokyo committed Mar 31, 2022
2 parents 008eb42 + 31af222 commit 2fcbd03
Show file tree
Hide file tree
Showing 16 changed files with 102 additions and 25 deletions.
12 changes: 12 additions & 0 deletions app/controllers/application_controller.rb
@@ -1,7 +1,19 @@
class ApplicationController < ActionController::Base
before_action :set_search_posts_form
add_flash_types :success, :info, :warning, :danger

private

def not_authenticated
redirect_to login_path, warning: 'ログインしてください'
end

# ヘッダー部分(=共通部分)に検索フォームを置くのでApplicationControllerに実装する
def set_search_posts_form
@search_form = SearchPostsForm.new(search_post_params)
end

def search_post_params
params.fetch(:q, {}).permit(:body, :comment_body, :username)
end
end
2 changes: 1 addition & 1 deletion app/controllers/likes_controller.rb
@@ -1,6 +1,6 @@
class LikesController < ApplicationController
before_action :require_login, only: %i[create destroy]

def create
@post = Post.find(params[:post_id])
current_user.like(@post)
Expand Down
8 changes: 6 additions & 2 deletions app/controllers/posts_controller.rb
Expand Up @@ -2,8 +2,8 @@ class PostsController < ApplicationController
before_action :require_login, only: %i[new create edit update destroy]
def index
@posts = if logged_in?
current_user.feed.includes(:user).order(created_at: :desc).page(params[:page])
else
current_user.feed.includes(:user).order(created_at: :desc).page(params[:page])
else
Post.all.includes(:user).order(created_at: :desc).page(params[:page])
end
@users = User.recent(5)
Expand Down Expand Up @@ -50,6 +50,10 @@ def destroy
redirect_to posts_path, success: '投稿を削除しました'
end

def search
@posts = @search_form.search.includes(:user).page(params[:page]).order(created_at: :desc)
end

private

def post_params
Expand Down
5 changes: 2 additions & 3 deletions app/controllers/users_controller.rb
@@ -1,9 +1,8 @@
class UsersController < ApplicationController

def index
@users = User.all.page(params[:page])
end

def new
@user = User.new
end
Expand All @@ -20,7 +19,7 @@ def create
end

def show
@user = User.find(params[:id])
@user = User.find(params[:id])
end

private
Expand Down
22 changes: 22 additions & 0 deletions app/forms/search_posts_form.rb
@@ -0,0 +1,22 @@
class SearchPostsForm
include ActiveModel::Model
include ActiveModel::Attributes

attribute :body, :string
attribute :comment_body, :string
attribute :username, :string

def search
scope = Post.distinct
scope = splited_bodies.map { |splited_body| scope.body_contain(splited_body) }.inject { |result, scp| result.or(scp) } if body.present?
scope = scope.comment_body_contain(comment_body) if comment_body.present?
scope = scope.username_contain(username) if username.present?
scope
end

private

def splited_bodies
body.strip.split(/[[:blank:]]+/)
end
end
4 changes: 4 additions & 0 deletions app/models/post.rb
Expand Up @@ -27,4 +27,8 @@ class Post < ApplicationRecord
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :like_users, through: :likes, source: :user

scope :body_contain, ->(word) { where('posts.body LIKE ?', "%#{word}%") }
scope :comment_body_contain, ->(word) { joins(:comments).where('comments.body LIKE ?', "%#{word}%") }
scope :username_contain, ->(word) { joins(:user).where('username LIKE ?', "%#{word}%") }
end
11 changes: 8 additions & 3 deletions app/models/relationship.rb
Expand Up @@ -5,19 +5,24 @@
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# followed_id :integer not null
# follower_id :integer not null
# followed_id :bigint not null
# follower_id :bigint not null
#
# Indexes
#
# index_relationships_on_followed_id (followed_id)
# index_relationships_on_follower_id (follower_id)
# index_relationships_on_follower_id_and_followed_id (follower_id,followed_id) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (followed_id => users.id)
# fk_rails_... (follower_id => users.id)
#
class Relationship < ApplicationRecord
belongs_to :follower, class_name: 'User'
belongs_to :followed, class_name: 'User'
validates :follower_id, presence: true
validates :followed_id, presence: true
validates :follower_id, uniqueness: {scope: :followed_id}
validates :follower_id, uniqueness: { scope: :followed_id }
end
14 changes: 7 additions & 7 deletions app/models/user.rb
Expand Up @@ -29,16 +29,16 @@ class User < ApplicationRecord
has_many :likes, dependent: :destroy
has_many :like_posts, through: :likes, source: :post
has_many :active_relationships, class_name: 'Relationship',
foreign_key: 'follower_id',
dependent: :destroy
foreign_key: 'follower_id',
dependent: :destroy
has_many :passive_relationships, class_name: 'Relationship',
foreign_key: 'followed_id',
dependent: :destroy
foreign_key: 'followed_id',
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
has_many :followers, through: :passive_relationships, source: :follower

scope :recent, ->(count) { order(created_at: :desc).limit(count) }

def own?(object)
id == object.user_id
end
Expand Down
5 changes: 5 additions & 0 deletions app/views/posts/_search_form.html.slim
@@ -0,0 +1,5 @@
= form_with model: search_form, url: search_posts_path, scope: :q, class: 'form-inline my-2 my-lg-0 mr-auto', method: :get, local: true do |f|
= f.search_field :body, class: 'form-control mr-sm-2', placeholder: '本文'
= f.search_field :comment_body, class: 'form-control mr-sm-2', placeholder: 'コメント'
= f.search_field :username, class: 'form-control mr-sm-2', placeholder: 'ユーザー名'
= f.submit 'Search', class: 'btn btn-outline-success my-2 my-sm-0'
7 changes: 7 additions & 0 deletions app/views/posts/search.html.slim
@@ -0,0 +1,7 @@
.container
.row
.col-md-8.col-12.offset-md-2
h2.text-center
| 検索結果: #{@posts.total_count}
= render @posts
= paginate @posts
4 changes: 1 addition & 3 deletions app/views/shared/_before_login_header.html.slim
Expand Up @@ -3,9 +3,7 @@ nav.navbar.navbar-expand-lg.navbar-light.bg-white
button.navbar-toggler aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label=("Toggle navigation") data-target="#navbarTogglerDemo02" data-toggle="collapse" type="button"
span.navbar-toggler-icon
#navbarTogglerDemo02.collapse.navbar-collapse
form.form-inline.my-2.my-lg-0.mr-auto
input.form-control.mr-sm-2 placeholder="Search" type="search" /
button.btn.btn-outline-success.my-2.my-sm-0 type="submit" Search
= render 'posts/search_form', search_form: @search_form
ul.navbar-nav.mt-2.mt-lg-0
li.nav-item
= link_to 'ポスト一覧', posts_path, class: 'nav-link'
Expand Down
4 changes: 1 addition & 3 deletions app/views/shared/_header.html.slim
Expand Up @@ -3,9 +3,7 @@ nav.navbar.navbar-expand-lg.navbar-light.bg-white
button.navbar-toggler aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label=("Toggle navigation") data-target="#navbarTogglerDemo02" data-toggle="collapse" type="button"
span.navbar-toggler-icon
#navbarTogglerDemo02.collapse.navbar-collapse
form.form-inline.my-2.my-lg-0.mr-auto
input.form-control.mr-sm-2 placeholder="Search" type="search" /
button.btn.btn-outline-success.my-2.my-sm-0 type="submit" Search
= render 'posts/search_form', search_form: @search_form
ul.navbar-nav.mt-2.mt-lg-0
li.nav-item
= link_to new_post_path, class: 'nav-link' do
Expand Down
4 changes: 4 additions & 0 deletions config/routes.rb
Expand Up @@ -9,6 +9,7 @@
# POST /users(.:format) users#create
# new_user GET /users/new(.:format) users#new
# user GET /users/:id(.:format) users#show
# search_posts GET /posts/search(.:format) posts#search
# post_comments GET /posts/:post_id/comments(.:format) comments#index
# POST /posts/:post_id/comments(.:format) comments#create
# new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
Expand Down Expand Up @@ -44,6 +45,9 @@

resources :users, only: %i[new create index show]
resources :posts, shallow: true do
collection do
get :search
end
resources :comments
end
resources :likes, only: %i[create destroy]
Expand Down
@@ -0,0 +1,11 @@
class ChangeFolloweridAndFollowedidOfRelationships < ActiveRecord::Migration[5.2]
def up
change_column :relationships, :follower_id, :bigint, null: false
change_column :relationships, :followed_id, :bigint, null: false
end

def down
change_column :relationships, :follower_id, :integer, null: false
change_column :relationships, :followed_id, :integer, null: false
end
end
@@ -0,0 +1,6 @@
class AddForeignKeyToFollowerIdAndFollowedId < ActiveRecord::Migration[5.2]
def change
add_foreign_key :relationships, :users, column: :follower_id
add_foreign_key :relationships, :users, column: :followed_id
end
end
8 changes: 5 additions & 3 deletions db/schema.rb
Expand Up @@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2022_03_16_144739) do
ActiveRecord::Schema.define(version: 2022_03_26_092430) do

create_table "comments", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb3", force: :cascade do |t|
t.bigint "user_id"
Expand Down Expand Up @@ -42,8 +42,8 @@
end

create_table "relationships", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb3", force: :cascade do |t|
t.integer "follower_id", null: false
t.integer "followed_id", null: false
t.bigint "follower_id", null: false
t.bigint "followed_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["followed_id"], name: "index_relationships_on_followed_id"
Expand All @@ -67,4 +67,6 @@
add_foreign_key "likes", "posts"
add_foreign_key "likes", "users"
add_foreign_key "posts", "users"
add_foreign_key "relationships", "users", column: "followed_id"
add_foreign_key "relationships", "users", column: "follower_id"
end

0 comments on commit 2fcbd03

Please sign in to comment.