0
0

More than 1 year has passed since last update.

【超簡単】Rails カレンダー導入方法 (シンプルカレンダー,simple_calendar)

Last updated at Posted at 2022-12-08

はじめに

Twitterライクのアプリを作っており、タスクや予定の管理などにカレンダーを導入したいと思った方に向けての執筆です!

公式と異なり、scaffoldなしで実装しております!
ご自身の作成中のアプリに必要箇所を取り入れてもらえればと思います!

完成形

日時を指定して投稿すると、カレンダー内のその日時に投稿が表示されます!

image.png

実装方法

まずはgemをインストールします。
gemfileに以下のコードを記入します!

Gemfile
gem 'simple_calendar', '~> 2.0'
ターミナル
 $ bundle install

今回はカレンダーに出力したいため :start_timeカラムを新たに作成します!

ターミナル
 $ rails g migration AddStart_TimeToTweets start_time:datetime
ターミナル
$ rails db:migrate

,:start_timeをコントローラーの最終行付近に記入しましょう!(下記コードを参考に!)

/app/controllers/tweets_controller.rb
class TweetsController < ApplicationController

  private

  def tweet_parameter
    params.require(:tweet).permit(:title, :body, :start_time)
  end

end
/app/views/tweets/index.html.erb
<h1>カレンダーアプリ</h1>

<table>
  <thead>
    <tr>
      <th>タイトル</th>
      <th>時間</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @tweets.each do |t| %>
      <tr>
        <td><%= t.title %></td>
        <td><%= t.start_time.strftime("%Y-%m-%d %H:%M") %></td>
        <td><%= link_to '詳細', t %></td>
        <td><%= link_to '編集', edit_tweet_path(t.id) %></td>
        <td><%= link_to '削除',blog_path(t.id), method: :delete, data: { confirm: '本当に削除しますか?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'カレンダーを書く', new_tweet_path %>

<%= month_calendar events: @tweets do |date, tweets| %>
  <%= date.day %>

  <% tweets.each do |tweet| %>
    <div>
      <%= link_to tweet.title, tweet %>
    </div>
  <% end %>
<% end %>

.strftime("%Y-%m-%d %H:%M")を記述することによって日本時間に変更することができます。

/app/views/tweets/new.html.erb
<%= form_with(model: @tweet, local: true) do |f| %>

  <div class="title">
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>

    <div class="time">
    <%= f.label :start_time %>
    <%= f.datetime_select :start_time %>
  </div>
  
  <div class="content">
    <%= f.label :body %>
    <%= f.text_field :body %>
  </div>


  <div class="submit">
    <%= f.submit %>
  </div>

<% end %>

カレンダーの見た目を整えるために以下のコードを実行してください

ターミナル
 $ rails g simple_calendar:views

以下の4つが作成されて見た目が整います!

      create  app/views/simple_calendar
      create  app/views/simple_calendar/_calendar.html.erb
      create  app/views/simple_calendar/_month_calendar.html.erb
      create  app/views/simple_calendar/_week_calendar.html.erb

最後にapplication.scssに記述を追加します!

/app/assets/stylesheets/application.css
/*
 *= require simple_calendar #ここに追記します
 *= require_tree .
 *= require_self
 */

 
以上で完成です!!

image.png

参考

公式ドキュメント
https://github.com/excid3/simple_calendar

最後に

不備等ございましたらコメントにて教えていただけると幸いです!
ここまで読んでいただきありがとうございました!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0