Yuto Blog

Yuto Blog

Tag: Rails
48 articles

【Gem】kaminari で一つのページで複数のペイジング

Controller ruby @topics = Topic.page(params[:topics_page]).per(5) @activities = Activity.page(params[:activities_page]).per(10) View ruby = paginate @topics, param_name: 'topics_page' = paginate @activities, param_name: 'activities_page'
Created by Yuto at 2022-01-21 17:42

【 Ruby on Rails 】自分のFlash message をカスタムする

ruby:app/controllers/application_controller.rb class ApplicationController add_flash_types :good, :bad end ruby:app/controllers/users_controller.rb class UsersController < ApplicationController def create redirect_to root_path, good: "Created user!" end end ruby:app/views/users/index.html.erb <%= good %>
Created by Yuto at 2022-01-21 17:42

【Ruby on Rails】Foundation5 flash message with slim

ruby:app/views/layouts/_message.html.slim - flash.each do |name, msg| - if msg.is_a?(String) div data-alert='' class="alert-box round #{name.to_s == 'notice' ? 'success' : 'alert'}" = content_tag :div, msg a href='#' class='close' &times;
Created by Yuto at 2022-01-21 17:42

【 Ruby on Rails】複数のOmniauth

>>> アプリケーションはこちらです <<< (http://renshu-multiple-omniauth.herokuapp.com/) 参考:Bootstrapの開発環境を自動的に作る (http://qiita.com/YutoYasunaga/items/f53e62d850570eb85e4f) Screen Shot 2015-05-27 at 20.28.11.png https://qiita-image-store.s3.amazonaws.com/0/35605/d4659969-7c74-3230-b216-478692ddab53.png ruby:Gemfile gem 'omniauth-facebook' gem 'omniauth-twitter' gem 'omniauth-google-oauth2' gem 'omniauth-tumblr' gem 'omniauth-amazon' ```ruby:config/devvariables.rb ENV['FACEBOOKKEY'] =...
Created by Yuto at 2022-01-21 17:42

[Ruby on Rails] Devise + Omniauth Authentication

Sample Application (https://yuto-devise-omniauth.herokuapp.com/) ruby:Gemfile gem 'devise' gem 'omniauth' gem 'omniauth-facebook' gem 'omniauth-twitter' gem 'paperclip' gem 'fog' rails g devise:install rails g devise User rails g devise:controllers users rails g migration AddAttributesToUsers name uid provider token rails g paperclip user image ruby:config/routes.rb devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks', registrations:...
Created by Yuto at 2022-01-21 17:42

[Ruby on Rails] SubModel in Model

Category Sub Category Sub Category Sub Category ```ruby:migrate.rb class CreateCategories < ActiveRecord::Migration[5.0] def change create_table :categories do |t| t.string :name t.references :parent t.timestamps end end end ``` ruby:model.rb class Category < ApplicationRecord has_many :categories, class_name: 'Category', foreign_key: 'parent_id', dependent: :destroy belongs_to :parent, class_name: 'Category', optional: true end c.parent c.categories
Created by Yuto at 2022-01-21 17:42

Ruby on Rails アプリにVuetifyとFontAwesomeの導入

Vuetify導入 yarn add vuetify @fortawesome/fontawesome-free ```javascript:app/javascript/packs/plugins/vuetify.js import Vue from 'vue' import Vuetify from 'vuetify' import "vuetify/dist/vuetify.min.css" import '@fortawesome/fontawesome-free/css/all.css' Vue.use(Vuetify) export default new Vuetify({ icons: { iconfont: 'fa', } }) ``` ```javascript:app/javascript/packs/main.js import vuetify from './plugins/vuetify' document.addEventListener('DOMContentLoaded', () => { const app = new...
Updated by Yuto at 2022-01-21 17:24

Ruby on Rails でFCMを使う時のメモ

click_actionを反映させる firebase-messaging-sw.jsのトップにnotificationclickイベントを追加すればいいらしいです。 ```javascript:public/firebase-messaging-sw.js // Notification click self.addEventListener('notificationclick', function(event) { let url = event.notification.data.FCM_MSG.data.url; event.notification.close(); // Android needs explicit close. event.waitUntil( clients.matchAll({ includeUncontrolled: true, type: 'window' }).then( windowClients => { // Check if there is already a window/tab open...
Created by Yuto at 2022-01-21 17:22

Ruby on Rails 6にTailwindCSSを導入(Gemを使わず)

Yarnで必要なものをインストールする yarn add tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9 tailwind.config.jsファイルを生成する yarn tailwindcss init app/javascript/packs/tailwind.config.js javascript:app/javascript/packs/tailwind.config.js module.exports = { purge: [ './app/**/*.html.erb', './app/**/*.html.slim', './app/helpers/**/*.rb', './app/javascript/packs/**/*.js', ], //...
Updated by Yuto at 2022-01-20 23:55
DockerでMailcatcherを使ってRuby on Rails開発環境のメールを受信する

DockerでMailcatcherを使ってRuby on Rails開発環境のメールを受信する

Mailcatcherの概要は公式サイトで色々記載されています:https://mailcatcher.me letter_opener も Ruby on Rails 開発環境のメールがテストできるが、個人的には Mailcatcher の方が便利で使いやすいので、よく使います。 docker-compose設定 yaml:docker-compose.yml mailcatcher: image: schickling/mailcatcher container_name: mailcatcher ports: - '1080:1080' - '1025:1025' Dockerを起動したら「localhost:1080」で管理画面にアクセスできます。 スクリーンショット 0003-10-30 22.10.33.png...
Updated by Yuto at 2022-01-20 23:55

【Ruby on Rails】active_model_serializersのキーをキャメルケースにする方法

activemodelserializersはデフォルトRuby風のスネークケースでレスポンスを返しますが、キャメルケースにするのは簡単で、イニシャライザフォルダの中で定義すればいいです。 ruby:config/initializers/active_model_serializers.rb ActiveModelSerializers.config.key_transform = :camel_lower サーバーの再起動が必要です
Updated by Yuto at 2022-01-20 23:55

Ruby on RailsでWebpackerのエイリアスを設定する方法

```javascript:config/webpack/environment.js const { resolve } = require('path') environment.config.merge({ resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('app/javascript/packs'), '&': resolve('app/javascript/packs/components'), }, }, }) ``` サーバーの再起動が必要です。
Updated by Yuto at 2022-01-20 23:55

【Ruby on Rails】EC2でwheneverを使ってcrontabを設定する時のハマったことの解決

wheneverというのはRuby on Railsのgemであり、crontabを設定する時によく使われています。 使い方 使い方はGithubホームページ (https://github.com/javan/whenever)に詳しく記載されていますが、主に使うのは下記になります。 Gemfileに追加 ruby:Gemfile gem 'whenever', require: false インストール bundle exec wheneverize . schedule.rbファイルの内容を確認する whenever 開発環境でcrontabを更新する whenever --update-crontab --set environment='development' Capistranoに入れる ruby:config/deploy.rb set :whenever_roles, -> { :app } ruby:Capfile require...
Updated by Yuto at 2022-01-20 23:55

Ruby on Rails 6にforeman導入メモ

gem導入 ruby:Gemfile gem 'foreman', group: :development Procfile.devを実行するbin/server作成 bin/server #!/bin/bash -i bundle install bundle exec foreman start -f Procfile.dev コマンドを実行するProcfile.dev作成 Procfile.dev web: /bin/sh -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" webpacker: ./bin/webpack-dev-server bin/serverの権限変更 chmod 777 bin/server サーバースタート bin/server
Updated by Yuto at 2022-01-20 23:55

PG::UniqueViolation: ERROR: duplicate key value violates unique constraintエラーの解決

PGデータベースにデータをインポートの後など、このエラーが発生する場合があります。 PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "<sample_tables>_pkey" 原因 データインポートなどの場合、PostgreSQLが指定したカラムの最大値を取ってくれず、別に保存してある最大値になってしまいます。 解決 Railsコンソールで以下のコードを実行すれば治ります。 ruby ActiveRecord::Base.connection.tables.each do |t| ActiveRecord::Base.connection.reset_pk_sequence!(t) end
Updated by Yuto at 2022-01-20 23:55

【Ruby on Rails】WebpackerでBootstrap、jQueryを導入方法

Webpackerのインストール ruby:Gemfile gem "webpacker" bundle install rails webpacker:install Bootstrapの導入 yarn add bootstrap@4.3.1 jquery popper.js ```javascript:webpacker/environment.js const { environment } = require('@rails/webpacker') // ↓↓↓ const webpack = require('webpack') environment.plugins.append( 'Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', Popper: ['popper.js', 'default'] }) ) // ↑↑↑ module.exports =...
Updated by Yuto at 2022-01-20 23:55

【Ruby on Rails】WebpackerでFontAwesomeを導入方法

Gemのインストール 必須ではないですが、Viewでiconメソッドを使うならば、Gemをインストールする必要です。 ruby:Gemfile gem "font-awesome-sass" FontAwesomeの導入 yarn add @fortawesome/fontawesome-free javascript:app/javascript/packs/application.js import "@fortawesome/fontawesome-free/js/all" css:app/javascripts/src/application.scss @import "@fortawesome/fontawesome-free/scss/fontawesome"; >>> FontAwesome free icons (https://fontawesome.com/icons?d=gallery&m=free)
Updated by Yuto at 2022-01-20 23:55

【Ruby on Rails】Webpackerでcocoonを導入方法

cocoonを使うなら、jQueryが必要なので、WebpackerでjQueryを導入方法はこちらです: 【Ruby on Rails】WebpackerでBootstrap、jQueryを導入方法 (https://qiita.com/YutoYasunaga/items/9a7eaa0a4ca898535912) ruby:Gemfile gem "cocoon" 以下のファイルをダウンロードして、app/javascript/src/に保存する。 https://github.com/nathanvda/cocoon/blob/master/app/assets/javascripts/cocoon.js javascript:app/javascript/packs/application.js require("../src/cocoon");
Updated by Yuto at 2022-01-20 23:55
【Ruby on Rails】Hướng dẫn làm chức năng sort với jquery-ui sortable

【Ruby on Rails】Hướng dẫn làm chức năng sort với jquery-ui sortable

Cài đặt jQuery và jQuery-ui yarn add popper.js jquery jquery-ui ```javascript:config/webpack/environment.js const { environment } = require('@rails/webpacker') // Add const webpack = require('webpack') environment.plugins.append( 'Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', Popper: ['popper.js', 'default'] }) ) // Add module.exports =...
Updated by Yuto at 2021-06-18 17:19
Phạm vi của biến và hằng trong Ruby

Phạm vi của biến và hằng trong Ruby

Bảng dưới đây mô tả về quy tắc đặt tên và phạm vi sử dụng của biến (variable) và hằng (constant) trong ngôn ngữ lập trình Ruby. Trong Ruby có những loại biến số: - Local variable - Global variable - Class variable - Instance variable Loại biến số được xác định dựa vào cách đặt tên. Tùy thuộc vào từng loại biến mà phạm vi sử dụng và kết quả trả về khi tham chiếu biến chưa được khai báo sẽ khác nhau. Quy tắc đặt tên biến và hằng | Loại biến và hằng | Quy tắc đặt tên | Phạm vi sử dụng | Kết...
Updated by Yuto at 2021-06-04 09:59