<%= post.title %>
<%= post.content %>
<%= link_to "I'm inter
動的に背景画像を変更する(Ruby on rails,JavaScript)
#はじめに
画像アドレスを入力することで、
背景画像を動的に変更する方法について書いていきます
#実行
基本となるビューファイルは次のようにします。“`haml:wall.haml.html
.body
= text_area “object_name”, {class: “wall-url”},{id: “wall-url”}
.wall-btn 画像を変える“`
`texr_area`が画像アドレスを張り付ける部分で、`.wall-btn`を押したら画像を変わるものとします。次にJavaScriptです。(jQueryで書いています)
“`javascript:wall.js
$(function(){
$(“.wall-btn”).on(“click”,function(){
})
});
“`
これで、`.wall-btn`をクリックした時に発火する関数ができました。
次は、処理の内容を書いていきます。“`javascript:wall.js
$(function(){
$(“.wall-btn”).on(“click”,
【完全版】MacでRails環境構築する手順の全て
## この記事は
**初心者でも迷わず環境構築ができるよう、1つ1つの手順を丁寧に解説した記事**です。
なるべく「どうしてこのコマンドを実行するのか」も解説するようにしています。**「環境構築が苦手、よくわからない」**という方は、ぜひ参考にしていただければと思います。
また「railsのバージョン指定がうまくいかない…」と悩んでいる方にも参考になると思います。※もしこれを読んでもうまくいかなければ、ぜひ積極的にコメントいただけますと幸いです!
## マシンスペック
参考までに、私のマシンスペックは以下の通りです。– macOS Catalina 10.15.3
– MacBook Air (Retina, 13-inch, 2018)
– Intel Core i5
– メモリ 8GB## Ruby, Railsのバージョン
それぞれ下記バージョンで構築することを目指します。– Ruby 2.5.7
– Rails 5.2.3## 全体の流れ
この順番でインストールしていきます。1. rbenv(Rubyのバージョン管理ツール)
2. Ruby
3
Railsのenumを読む
Railsのソースコードを読みます。
enumに関して
“`ruby
class User < ApplicationRecord binding.pry enum status: { active: 0, inactive: 1 } end ``` bindingを使ってコードの中に入っていく。 ``` 153: attr_reader :name, :mapping, :subtype 154: end 155: 156: def enum(definitions) 157: klass = self => 158: enum_prefix = definitions.delete(:_prefix)
159: enum_suffix = definitions.delete(:_suffix)
160: enum_scopes = definitions.delete(:_scopes)
161: def
deviseのcontrollerをインストールしていない場合は、ログイン後のユーザー作成は出来ないよって話。
自分用メモ
macOS Catalina 10.15.3
ruby 2.6.3
rails 5.2.4ログイン機能なしの作業報告用アプリを作成。
ユーザーを作成して、devise後付けでだが、deviseのcontrollerは無し。(インストールしなくても裏で作動する)
deviseのmodelとviewはインストール。deviseのcontrollerをインストールしていない場合は、ログイン後のユーザー作成は出来ない。
と言うか、社内用を想定してのアプリだから、
ユーザー登録=ユーザー作成
よって新規ユーザー作成のリンクは削除。
どうしても作成したい場合は、ログインする前のログイン画面にリンクを持ってくる。
している場合は、こちらを参照(管理者権限でユーザー作成)
https://qiita.com/MasatoYoshioka@github/items/7de96ac05bc0c17b7535
[rails,aws]budlerのバージョンが変更できないエラーの解決方法
#1.エラーが出るまでの経緯
筆者はチーム開発のローカル開発でbundler-2.0.1を使ってきたのですが、githubからのセキュリティのためのバージョンアップを行なった際に、誤って本番環境のbundlerのバージョンを2.1.4にあげてしまいました。しかし不要なバージョンアップはバグの原因になるため極力避けたいので、ダウングレード(最新バージョンを削除し使いたいバージョンbundlerをインストール)しようとしました。その結果下記のような結果となりました。
“`
#使いたいbundlerのバージョンを指定(インストール)
[ec2-user@ip-111-11-11-11 freemarket_sample_62d]$ gem install bundler -v 2.0.1
Successfully installed bundler-2.0.1
Parsing documentation for bundler-2.0.1
Done installing documentation for bundler after 3 seconds
1 gem installed
Rails on HerokuなアプリからFirestoreにアクセスしたい場合の実装例&ハマりどころ
# 背景
Firestoreを使用する場合、大抵はフロントエンドから直接クエリを発行してDB操作を行うのだろうが、実装者のスキルセットや要件によってはFirestoreの操作に関する処理をサーバーサイドに置きたい場合もある。例えば以下のような事例が見つかった。– [既にREST API/RDSが存在しており、部分的にFirestoreを利用したハイブリッドな構成にしたい場合](https://speakerdeck.com/temoki/ruby-on-rails-plus-cloud-firestore-falsehaiburitudogou-cheng-degou-zhu-sururiarutaimutiyatutoji-neng)
– [小規模なアプリの開発時、ちょっとしたデータ置き場としてFirestoreを利用したい場合](https://tech.studyplus.co.jp/entry/2019/03/11/094557)
– [フロントエンドにDBへの書き込み処理を実装することによって生じる実装の煩雑さを回避したい場合](https://webuilder240.
【Rails】Rakeタスクに:environmentがないとNameErrorが出る
## エラー
Rakeタスクを実行したときに、`NameError: uninitialized constant ClassName`が出る。
“`rb:send_summary_mail.rake
namespace :send_summary_mail do
desc ‘管理者に記事数一覧をメール送信する’
task :send_mail do
SummaryMailer.daily.deliver_now
puts ‘メールを送信しました’
end
end
“`“`terminal
$ rake send_summary_mail:send_mail
rake aborted!
NameError: uninitialized constant SummaryMailer
/Users/k_end/workspace/application/lib/tasks/send_mail_summary.rake:4:in `block (2 levels) in‘
Tasks: TOP => send_su
【RSpec】toggleされた要素へのクリック対応
#はじめに
RSpecでユーザー登録の統合テストをかいているときに、
toggleされた要素に対するクリックのやり方でつまづきました。
僕と同じ初学者の方の参考になりましたら幸いです。#RSpecでのテスト
RSpecでの簡単なテストを一部抜粋。
ルートページで「新規登録」ボタンをおすと、
「ユーザーの新規登録」と記載されているページに遷移することを確認するテスト。“`
it ‘ユーザー登録ページが表示される’ do
visit root_path
click_on ‘新規登録’
expect(page).to have_content ‘ユーザーの新規登録’
end
“`下記エラーが発生。
“`
Failure/Error: click_on ‘新規登録’Capybara::ElementNotFound:
Unable to find visible link or button “新規登録”
“`
slimには`=link_to signup_path, class: ‘nav-link’ do | 新規登
【Rails】/users/:id ではなく/:username にする
# 理想
—
## やり方
to_paramを使用する“`ruby:user.rb
class User < ActiveRecord::Base validates_presence_of :username validates_uniqueness_of :username, case_sensitive: false def to_param username end ``` --- ```ruby:users_controller.rb class UsersController < ApplicationController def show @user = User.find_by(us
【Rails】saveやcreateメソッドでのエラーが発生した時のエラーメッセージの出し方
#saveメソッド
“`
irb(main):005:0> user.save
(0.3ms) BEGIN
User Exists (7.7ms) SELECT 1 AS one FROM `users` WHERE `users`.`email` IS NULL LIMIT 1
(0.2ms) ROLLBACK
=> false
“`
saveのみだとfalseが返されるのみ。エラーメッセージが出てこないので、エラー原因が特定できない。そういった場合saveの後に「!」をつけるとエラーメッセージが表示される。“`
irb(main):006:0> user.save!
(0.3ms) BEGIN
User Exists (0.4ms) SELECT 1 AS one FROM `users` WHERE `users`.`email` IS NULL LIMIT 1
(0.1ms) ROLLBACK
Traceback (most recent call last):
1: from (irb):6
Acti
[rails] http ステータスコードのsymbol一覧確認方法メモ
rspecでレスポンス結果200のhttp statusである、という場合は下記のように書ける
“`ruby
expect(response).to have_http_status(200)
expect(response).to have_http_status(:ok)
“`下の:okといったsymbolのステータスコードを指定する場合、どんな値が定義されているか分からず都度調べたりしていたが、下記の定数に定義されているらしい
“`ruby
[5] pry(main)> Rack::Utils::SYMBOL_TO_STATUS_CODE
=> {:continue=>100,
:switching_protocols=>101,
:processing=>102,
:ok=>200,
:created=>201,
“`そもそもドキュメントの頭に書いてあったし、Railsでも使っているよね。。。
参考
https://relishapp.com/rspec/rspec-rails/docs/matchers/have-http-status-matc
Rails + React + AjaxでCRUDのサンプルプロジェクト [Hello World]
React初心者が公式サイトで基礎を学んだ後に作るReact + AjaxによるCRUD(作成/読み込み/更新/削除)のサンプルプロジェクトです。
![react_crud_1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597258/58bb3725-2d2d-0a6c-df9e-57745bd37b48.png)
Twitterのように「つぶやき」を投稿可能で編集/削除もできます。動作確認はChrome、FireFox、Microsoft Edge、IE11です。恐らくマックさんのブラウザでも動作するはずです。
Model#xxx_before_type_cast / Get instance / Not type casted inputs ( attributes ) / e.g invalid Date to be nil / #Rails
“`rb
# == Schema Information
#
# Table name: users
#
# id :bigint not null, primary key
# birth_date :date not nullclass User < ApplicationRecord end # Valid Date # type casted # be Date User.new(birth_date: "19800229").birth_date # => Fri, 29 Feb 1980
# valid Date
# before Type Casted
# be String
User.new(birth_date: “19800229”).birth_date_before_type_cast
# => “19800229”# Invalid Date
# type casted
# be nil
User.new(birth_da
xxx_before_type_cast / #Rails で 不正な日付を ActiveRecord に渡すと nil に変換されてしまうため 、タイプキャストする前の入力値を得る
“`rb
# == Schema Information
#
# Table name: users
#
# id :bigint not null, primary key
# birth_date :date not nullclass User < ApplicationRecord end # Valid Date # type casted # be Date User.new(birth_date: "19800229").birth_date # => Fri, 29 Feb 1980
# valid Date
# before Type Casted
# be String
User.new(birth_date: “19800229”).birth_date_before_type_cast
# => “19800229”# Invalid Date
# type casted
# be nil
User.new(birth_da
【Rails不定期連載】#1 DockerでRailsの環境構築
アウトプットの練習 & 初心に帰って基礎からRailsを見直してこうと思います。
不定期に更新します。今回はRuby on Railsの環境構築。
今回はDockerでRailsチュートリアルを進めていくためのRailsプロジェクトを作ります。
[rbenv]([https://github.com/rbenv/rbenv](https://github.com/rbenv/rbenv))などを用いたローカルでの環境構築ではないです。## 前置き
### 前提として…
– 以下の場合はローカルでの環境構築を勧めます
– railsの環境構築1度もしたことない
– dockerを使った開発をしたことがない(Dockerfileの記述がわからない)
### アプリケーション要件
– ruby 2.6.5
– rails 6.2.0
– sqlite3
– webpacker、springはとりあえず不要なので除くすごいざっくりですが、こんなイメージ、コンテナを作るのがゴールです。
## レッツ環境構築
### STEP1 rails newコマ
1つの投稿で複数の画像をプレビュー表示させながら保存する
##概要
Railsアプリケーションにて、投稿に紐付く画像を複数枚、プレビュー表示させながら投稿できる機能を実装したので備忘録としてまとめます。
ProductにImageが紐付きます。
ビューのところは特にもっといい方法があるんだろうなと思っておりますが、
改善点や間違いがあれば是非コメントいただけますと幸いです!##完成イメージ
MySQL内
rails sができない時の対処方# rails sを叩くとエラー出力
spring stopを試して解決できず少し詰まったので備忘録として残します。
“`
/Users/arakitakuro/.rbenv/versions/2.5.1/lib/ruby/2.5.0/fileutils.rb:90: warning: already initialized constant FileUtils::VERSION
/Users/arakitakuro/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/fileutils-1.4.1/lib/fileutils.rb:105: warning: previous definition of VERSION was here
/Users/arakitakuro/.rbenv/versions/2.5.1/lib/ruby/2.5.0/fileutils.rb:1188: warning: already initialized constant FileUtils::Entry_::S_IF_DOOR
/Users/ara
ログインshellの変更、そしてrbenvでインストールしたRubyをデフォルトにする方法
ゴールはrbenvでインストールしたRubyをデフォルトで開けること。
→その設定が書かれた.bash_profileというファイルを
デフォルトで読み込んでもらえないというのが問題でした。前回記事
https://qiita.com/hacchi_mom/items/2095e6ac7aecd03f131a# .bash_profileについて
まず.bash_profileってなんなんだというところから調べると
【ログインの際に読み込まれる設定ファイル】とのこと。そして重要なのは、その設定ファイルは
【ログインshellがbashのときに読み込まれるもの】
ということ!!!!# ログインshell問題
ログインshellとはログイン時に起動するshellのことですが
そもそも私の起動時のログインshellはbashではなくzshだったのです。Terminal起動時に毎回まず`bash`と一度打ってから
全ての作業を始めておりました…そういうもんだと思っていました。笑初歩すぎること書いててすいません。。。
だから.bash_profileを読み込んでもら
[ruby,rails]gemのバージョンのdefault設定解除方法
#1.エラーの例
“`
$gem uninstall railties -v ‘6.0.2.1’ #アンインストールコマンドです
~中略~
gem “railties” cannot be uninstalled because it is a default gem #エラー文
“`railsやその周辺のgemをダウングレードするべく、最新のgemに対し上記のアンインストールコマンドを打ったところその下のようにエラー文をだしました。そのエラー解決についてあまりネット上に記載がなかったので、解決方法を記載します
※railsなどのgemのバージョンを下げるには”インストールされている最新のgemのバージョン=反映させたいgemバージョン”とするため、必要なバージョン以上の全てのバージョンをアンインストールする必要があります#2.エラーの原因
コマンドの意味をよく調べずに`gem update –default`というコマンドを打ったところ、local( /Users/kontatomoya/.rbenv/versions/2.5.1/lib/ruby/gems/2.5