- 投稿日:2022-04-02T21:57:33+09:00
定数だけを切り出したファイルを作り、複数クラスで使えるようにする
やりたいこと Rubyで定義した定数を他のクラスでも使いたいとき、クラス名::定数名のように書くと思う。 ほとんどの場合は問題ないけれど、ときどき下記のような違和感や問題を感じるときがある。 関連が強いor内容が似てる複数のクラスで同じ定数を使いたいとき、特定のクラスにだけ定数を記載し、他のクラスではクラス名::定数名と書くことへの違和感 クラス名が長いときなどに読みづらくなる なのでより読みやすい、使いやすい形にしたかった。 ( config/initializers/constants.rbで共通の定数を設定する方法もあるが、そこまで全体的に使いたい訳でもない場合を想定 ) どうするか 定数用のmoduleを作って、定数を使いたいクラスにそのmoduleを読み込んで使う やりかた moduleを作成し、定数を記載する 使いたいクラスで読み込む ① moduleを作って定数を書く HogeConstants.rbを作成し、定数を書く module HogeConstants NEKO = "neko".freeze! INU = "inu".freeze! DORAEMON = "doraemon".freeze! end ②使いたいクラスで読み込む class Hoge < ApplicationRecord require "hoge_constants" include HogeConstants end moduleはincludesを使わないとエラー出るので注意。 これで複数のクラスで「クラス名::」を書かなくても定数が使える。 もっといい方法や、ツッコミあったら是非いただきたいです?
- 投稿日:2022-04-02T18:51:38+09:00
rails7からrails6にダウングレードした
Gemfileのバージョン変更 - gem "rails", "~> 7.0.2", ">= 7.0.2.3" + gem 'rails', '~> 6.0.4', '>= 6.0.4.7' コマンド実行 $ bundle update $ rails app:update (全てYES) $ rails s -b 0.0.0.0するとエラー起きるので、以下2点修正。 Gemfileにgem ‘listen’追加 group :development do # Use console on exceptions pages [https://github.com/rails/web-console] gem "web-console" gem 'listen' end config.ruからRails.application.load_server削除 config.ru - Rails.application.load_server マイグレーションしていきます。 $ rails db:reset $ rails db:migrate rails aborted! ArgumentError: Unknown migration version "7.0"; expected one of "4.2", "5.0", "5.1", "5.2", "6.0" db/migrate/****_create_users.rb - class CreateUsers < ActiveRecord::Migration[7.0] + class CreateUsers < ActiveRecord::Migration[6.0] rails aborted! NoMethodError: undefined method `define' for #ActiveRecord::Migration:0x0000ffff82c040e0 Did you mean? defined? db/schemes.rb - ActiveRecord::Schema[7.0].define(version: 2022_03_30_XXXXX) do + ActiveRecord::Schema.define(version: 2022_03_30_XXXXX) do rails aborted! NameError: undefined local variable or method `primary_abstract_class' models/application_record.rb class ApplicationRecord < ActiveRecord::Base - primary_abstract_class + self.abstract_class = true end 再度$ rails s -b 0.0.0.0実行し、http://localhost:3000/に表示される やったー!!
- 投稿日:2022-04-02T17:43:41+09:00
$ git remote add origin リポジトリURL を入力してfatal: remote origin already exists. とターミナルにエラーが表示された時の解決法
初めまして。プログラミングスクールに通っているso-heiです。現在2ヶ月目です。 自分の備忘録としてですが、同じエラーが出た方のお役に立てれば幸いです。 【問題】 $ git remote add origin git@github.com:ユーザ名/リポジトリ名.git ローカルリポジトリとリモートリポジトリの紐付けするために、上記をターミナルで入力すると表題のエラーが発生する。 【原因】 .git/configファイルに既にremote "origin”の設定が既に存在していた 【解決法】 ①remote "origin”の設定を削除 $ git remote rm origin 上記のコマンドで入力して.git/configファイルの remote "origin”の設定を削除する ②もう一度試してみる $ git remote add origin git@github.com:ユーザ名/リポジトリ名.git これでエラーは出なくなり、 この後にpushしましたが問題なく反映されました。 【参考になったサイト】 こちらの方のサイトを参考にしました。 詳しく説明されていますので、ぜひご覧ください。 https://pyoonn.hatenablog.com/entry/2014/10/29/191744
- 投稿日:2022-04-02T17:43:41+09:00
【Git】$ git remote add origin リポジトリURL を入力してfatal: remote origin already exists. とターミナルにエラーが表示された時の解決法
初めまして。プログラミングスクールに通っているso-heiです。現在2ヶ月目です。 自分の備忘録としてですが、同じエラーが出た方のお役に立てれば幸いです。 【問題】 $ git remote add origin git@github.com:ユーザ名/リポジトリ名.git ローカルリポジトリとリモートリポジトリの紐付けするために、上記をターミナルで入力すると表題のエラーが発生する。 【原因】 .git/configファイルに既にremote "origin”の設定が既に存在していた 【解決法】 ①remote "origin”の設定を削除 $ git remote rm origin 上記のコマンドで入力して.git/configファイルの remote "origin”の設定を削除する ②もう一度試してみる $ git remote add origin git@github.com:ユーザ名/リポジトリ名.git これでエラーは出なくなり、 この後にpushしましたが問題なく反映されました。 【参考になったサイト】 こちらの方のサイトを参考にしました。 詳しく説明されていますので、ぜひご覧ください。 https://pyoonn.hatenablog.com/entry/2014/10/29/191744
- 投稿日:2022-04-02T16:09:11+09:00
いいね Ajaxにする
Ajaxとは? ページを更新することなくページの内容だけを入れ替えられる。 ajaxの中核を支えているのはJavacriptの技術。 デメリットもあるらしいがそれを差し引いてもメリットがあると今は理解した。 何から手を出していいのかわからない。 早速実践 ボタン my_app/app/views/favorites/_favorite.html.erb <% if current_user.like?(micropost) %> <%= button_to user_favorite_path(current_user, micropost), method: :delete remote: :true do %> <%= micropost.liked.count %> <span style = "color:red;">♡</span> <% end %> <% else %> <%= button_to user_favorites_path(current_user, micropost), method: :post remote: :true do %> <%= micropost.liked.count %> <span >♡</span> <% end %> <% end %> :remote :trueでAjaxでリンクを処理ができるらしい。 コントローラ my_app/app/controllers/favorite/favorites_controller.rb class FavoritesController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] def create @micropost = Micropost.find_by(id: params[:format]) current_user.like(@micropost) respond_to do |format| format.html { redirect_to request.referer } format.js { redirect_to request.referer } end end def destroy @micropost = Micropost.find_by(id: params[:id]) current_user.unlike(@micropost) respond_to do |format| format.html { redirect_to request.referer } format.js end end end MVCのことを考えながら見てみると、 ボタン(オプション引数を使って)でコンローラに行ってビューに表示させる。 それにあっているのかな? JavaScriptが有効になっていても、まだ十分に対応できていない部分があります。 というのも、Ajaxリクエストを受信した場合は、 Railsが自動的にアクションと同じ名前を持つJavaScript用の埋め込みRuby(.js.erb)ファイル(create.js.erbやdestroy.js.erbなど)を呼び出すからです。 ユーザーをフォローしたときやフォロー解除したときにプロフィールページを更新するために、 私たちがこれから作成および編集しなければならないのは、まさにこれらのファイルです。 予想 ファイルを小分けにする理由はリアクションを早くするためなのかもしれない。 jqueryを使う CSS idで指定する ドル記号($)とCSS idを使って、DOM要素にアクセスする文法について知る必要があります。 例えばfollow_formの要素をjQueryで操作するには、次のようにアクセスします。 $("#follow_form") jQueryの文法はCSSの記法から影響を受けており、#シンボルを使ってCSSのidを指定します。 HTMLに表示させる 指定された要素の内側にあるHTMLを、引数の内容で更新します。 例えばフォロー用フォーム全体を"foobar"という文字列で置き換えたい場合は、 次のようなコードになります。 $("#follow_form").html("foobar") create.js.erbファイルでは、フォロー用のフォームをunfollowパーシャルで更新し、 フォロワーのカウントを更新するのにERbを使っています 予想 できるだけ小さいファイルにする方がいいのかな? ビュー app/views/microposts/_micropost.html.erb <li id="micropost-<%= micropost.id %>"> . . . <%= render 'microposts/favorite', micropost: micropost %> . . . </li> app/views/microposts/_favorite.html.erb <div id="like_form"> <% if current_user.like?(micropost) %> <%= render "microposts/unlike", micropost: micropost %> <% else %> <%= render "microposts/like", micropost: micropost %> <% end %> </div> app/views/microposts/_unlike.html.erb <%= button_to user_favorite_path(current_user, micropost), method: :delete ,remote: true do %> <%= micropost.liked.count %> <span style = "color:red;">♡</span> <% end %> app/views/microposts/_like.html.erb <%= button_to user_favorites_path(current_user, micropost), method: :post, remote: true do %> <%= micropost.liked.count %> <span >♡</span> <% end %> エラー ActionController::UnknownFormat app/views/favorites/create.js.erb $("#like_form").html("<%= escape_javascript(render 'microposts/like', micropost: @micropost) %>"); app/views/favorites/destroy.js.erb $("#like_form").html("<%= escape_javascript(render 'microposts/unlike', micropost: @micropost) %>"); できなかった。 current_user.like?(miropost)でcurrent_userがうまく機能しないらしい。 これからまた勉強し直して必ず身を結べるように努力する
- 投稿日:2022-04-02T10:12:44+09:00
Railsでlink_to deleteが出来ない
某オンラインスクールで学習4ヶ月目、 Railsにてオリジナルwebアプリを作成していて link_toの"削除"が実行できなくてぐるぐるしたので備忘録として。 dpテーブルに投稿したレコードを削除するため実装、削除出来ず。 <%= link_to "報告の削除", dp_path(@dp.id), method: :delete %> エラー画面も出ず、元の画面に戻ってきてしまう。 ログを見るとどうやらGETで動いている模様。 参考にした記事 https://qiita.com/mami3sansan/items/6a9710b3ffdc937aa5f3 https://nabelog.org/695/ https://takayuki-inoue.hatenablog.com/entry/2018/01/12/105846 その他いくつか読んでみたが、解決に至る糸口が見つからず。 上記記事等から得た知識を元に思い当たる節を探ってみたところ、 作成初期に放り込んでいた、bootstrap絡みの cssやらjavascriptあたりに要因がありそうな気配が。 (bootstrapは全然使いこなせず放置しておりました) で、その中のjavascriptが要因だった模様。 該当と思しきファイルをエイっと削除(これもイケナイような気もする)したところ、 無事にアプリ内のデータ削除が実行出来るようになりました。 訳も分からないまま適当に放り込まない、 ということを念頭に地道に勉強続けます。。。 ※ここの理解が違いますよ、等など教えていただけましたら有り難いです
- 投稿日:2022-04-02T02:50:39+09:00
【Docker】NameError: uninitialized constant Gem::Source 解消法【Rails】
はじめに 本記事は、プログラミング初学者、学習を進めていて疑問に思った点について調べた結果を備忘録も兼ねてまとめたものです。 そのため、記事の内容に誤りが含まれている可能性があります。ご容赦ください。 間違いを見つけた方は、お手数ですが、ご指摘いただけますと幸いです。 NameError: uninitialized constant Gem::Source 解消法 状況 以下の内容のDockerfileでdocker build -t <イメージ名> .実行後、docker run <イメージ名> rails new .したところ以前は発生しなかったNameError: uninitialized constant Gem::Sourceが発生しました。 Dockerfile FROM ruby:3.1.1 ENV APP_NAME=myapp ENV USER_NAME=myuser ENV TZ=Asia/Tokyo WORKDIR /${APP_NAME} COPY Gemfile /${APP_NAME}/Gemfile COPY Gemfile.lock /${APP_NAME}/Gemfile.lock RUN bundle install COPY entrypoint.sh /usr/bin/ RUN chmod +x /usr/bin/entrypoint.sh ENTRYPOINT ["entrypoint.sh"] RUN adduser ${USER_NAME} && \ chown -R ${USER_NAME} /${APP_NAME} && \ chown -R ${USER_NAME} ${GEM_HOME} USER ${USER_NAME} EXPOSE 3000 CMD ["rails", "server", "-b", "0.0.0.0"] ターミナル [12, #<Thread:0x0000ffffa5667c90 run>, #<NameError: uninitialized constant Gem::Source (defined?(@source) && @source) || Gem::Source::Installed.new ^^^^^^^^ Did you mean? Gem::SourceList>, ["/usr/local/lib/ruby/3.1.0/bundler/rubygems_ext.rb:18:in `source'", "/usr/local/lib/ruby/3.1.0/bundler/rubygems_ext.rb:50:in `extension_dir'", "/usr/local/lib/ruby/3.1.0/rubygems/basic_specification.rb:339:in `have_file?'", "/usr/local/lib/ruby/3.1.0/rubygems/basic_specification.rb:86:in `contains_requirable_file?'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:1038:in `block (2 levels) in find_in_unresolved_tree'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2555:in `block (2 levels) in traverse'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2550:in `each'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2550:in `block in traverse'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2548:in `each'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2548:in `traverse'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:1034:in `block in find_in_unresolved_tree'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:1033:in `each'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:1033:in `find_in_unresolved_tree'", "<internal:/usr/local/lib/ruby/3.1.0/rubygems/core_ext/kernel_require.rb>:114:in `require'", "/usr/local/lib/ruby/3.1.0/bundler/rubygems_ext.rb:18:in `source'", "/usr/local/lib/ruby/3.1.0/bundler/rubygems_ext.rb:50:in `extension_dir'", "/usr/local/lib/ruby/3.1.0/rubygems/basic_specification.rb:339:in `have_file?'", "/usr/local/lib/ruby/3.1.0/rubygems/basic_specification.rb:86:in `contains_requirable_file?'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:1038:in `block (2 levels) in find_in_unresolved_tree'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2555:in `block (2 levels) in traverse'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2550:in `each'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2550:in `block in traverse'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2548:in `each'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:2548:in `traverse'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:1034:in `block in find_in_unresolved_tree'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:1033:in `each'", "/usr/local/lib/ruby/3.1.0/rubygems/specification.rb:1033:in `find_in_unresolved_tree'", "<internal:/usr/local/lib/ruby/3.1.0/rubygems/core_ext/kernel_require.rb>:114:in `require'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/net-http-persistent/lib/net/http/persistent.rb:1:in `<top (required)>'", "/usr/local/lib/ruby/3.1.0/bundler/vendored_persistent.rb:11:in `require_relative'", "/usr/local/lib/ruby/3.1.0/bundler/vendored_persistent.rb:11:in `<top (required)>'", "/usr/local/lib/ruby/3.1.0/bundler/fetcher.rb:3:in `require_relative'", "/usr/local/lib/ruby/3.1.0/bundler/fetcher.rb:3:in `<top (required)>'", "<internal:/usr/local/lib/ruby/3.1.0/rubygems/core_ext/kernel_require.rb>:85:in `require'", "<internal:/usr/local/lib/ruby/3.1.0/rubygems/core_ext/kernel_require.rb>:85:in `require'", "/usr/local/lib/ruby/3.1.0/bundler/cli/install.rb:50:in `run'", "/usr/local/lib/ruby/3.1.0/bundler/cli.rb:255:in `block in install'", "/usr/local/lib/ruby/3.1.0/bundler/settings.rb:131:in `temporary'", "/usr/local/lib/ruby/3.1.0/bundler/cli.rb:254:in `install'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/thor/lib/thor/command.rb:27:in `run'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/thor/lib/thor/invocation.rb:127:in `invoke_command'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/thor/lib/thor.rb:392:in `dispatch'", "/usr/local/lib/ruby/3.1.0/bundler/cli.rb:31:in `dispatch'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/thor/lib/thor/base.rb:485:in `start'", "/usr/local/lib/ruby/3.1.0/bundler/cli.rb:25:in `start'", "/usr/local/lib/ruby/gems/3.1.0/gems/bundler-2.3.7/libexec/bundle:48:in `block in <main>'", "/usr/local/lib/ruby/3.1.0/bundler/friendly_errors.rb:103:in `with_friendly_errors'", "/usr/local/lib/ruby/gems/3.1.0/gems/bundler-2.3.7/libexec/bundle:36:in `<main>'"]] [12, #<Thread:0x0000ffffa5667c90 run>, #<RuntimeError: CRITICAL: RUBYGEMS_ACTIVATION_MONITOR.owned?: before false -> after true>, ["<internal:/usr/local/lib/ruby/3.1.0/rubygems/core_ext/kernel_require.rb>:167:in `ensure in require'", "<internal:/usr/local/lib/ruby/3.1.0/rubygems/core_ext/kernel_require.rb>:167:in `require'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/net-http-persistent/lib/net/http/persistent.rb:1:in `<top (required)>'", "/usr/local/lib/ruby/3.1.0/bundler/vendored_persistent.rb:11:in `require_relative'", "/usr/local/lib/ruby/3.1.0/bundler/vendored_persistent.rb:11:in `<top (required)>'", "/usr/local/lib/ruby/3.1.0/bundler/fetcher.rb:3:in `require_relative'", "/usr/local/lib/ruby/3.1.0/bundler/fetcher.rb:3:in `<top (required)>'", "<internal:/usr/local/lib/ruby/3.1.0/rubygems/core_ext/kernel_require.rb>:85:in `require'", "<internal:/usr/local/lib/ruby/3.1.0/rubygems/core_ext/kernel_require.rb>:85:in `require'", "/usr/local/lib/ruby/3.1.0/bundler/cli/install.rb:50:in `run'", "/usr/local/lib/ruby/3.1.0/bundler/cli.rb:255:in `block in install'", "/usr/local/lib/ruby/3.1.0/bundler/settings.rb:131:in `temporary'", "/usr/local/lib/ruby/3.1.0/bundler/cli.rb:254:in `install'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/thor/lib/thor/command.rb:27:in `run'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/thor/lib/thor/invocation.rb:127:in `invoke_command'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/thor/lib/thor.rb:392:in `dispatch'", "/usr/local/lib/ruby/3.1.0/bundler/cli.rb:31:in `dispatch'", "/usr/local/lib/ruby/3.1.0/bundler/vendor/thor/lib/thor/base.rb:485:in `start'", "/usr/local/lib/ruby/3.1.0/bundler/cli.rb:25:in `start'", "/usr/local/lib/ruby/gems/3.1.0/gems/bundler-2.3.7/libexec/bundle:48:in `block in <main>'", "/usr/local/lib/ruby/3.1.0/bundler/friendly_errors.rb:103:in `with_friendly_errors'", "/usr/local/lib/ruby/gems/3.1.0/gems/bundler-2.3.7/libexec/bundle:36:in `<main>'"]] /usr/local/lib/ruby/3.1.0/bundler/rubygems_ext.rb:18:in `source': uninitialized constant Gem::Source (NameError) (defined?(@source) && @source) || Gem::Source::Installed.new ^^^^^^^^ Did you mean? Gem::SourceList from /usr/local/lib/ruby/3.1.0/bundler/rubygems_ext.rb:50:in `extension_dir' from /usr/local/lib/ruby/3.1.0/rubygems/basic_specification.rb:339:in `have_file?' from /usr/local/lib/ruby/3.1.0/rubygems/basic_specification.rb:86:in `contains_requirable_file?' from /usr/local/lib/ruby/3.1.0/rubygems/specification.rb:1038:in `block (2 levels) in <省略> run bundle binstubs bundler Could not find gem 'sprockets-rails' in locally installed gems. rails importmap:install Could not find gem 'sprockets-rails' in locally installed gems. Run `bundle install` to install missing gems. rails turbo:install stimulus:install Could not find gem 'sprockets-rails' in locally installed gems. Run `bundle install` to install missing gems. 解決した方法 Bundlerをアップデートするために、Dockerfileを以下のように修正し、再度docker build -t <イメージ名> .実行後、docker run <イメージ名> rails new .することで解消しました。 Dockerfile FROM ruby:3.1.1 ENV APP_NAME=myapp ENV USER_NAME=myuser ENV TZ=Asia/Tokyo ENV BUNDLER_VERSION=2.3.10 WORKDIR /${APP_NAME} COPY Gemfile /${APP_NAME}/Gemfile COPY Gemfile.lock /${APP_NAME}/Gemfile.lock RUN gem install bundler -v ${BUNDLER_VERSION} && \ bundle install # Bundlerをアップデートできれば良いので # gem install bundler -v ${BUNDLER_VERSION}は以下のどちらかでも対応可能です。 # gem update --system (RubyGemsをアップデート) # gem update bundler (Bundlerを最新バージョンにアップデート) COPY entrypoint.sh /usr/bin/ RUN chmod +x /usr/bin/entrypoint.sh ENTRYPOINT ["entrypoint.sh"] RUN adduser ${USER_NAME} && \ chown -R ${USER_NAME} /${APP_NAME} && \ chown -R ${USER_NAME} ${GEM_HOME} USER ${USER_NAME} EXPOSE 3000 CMD ["rails", "server", "-b", "0.0.0.0"] ちなみに修正前のBundlerのバージョンは2.3.7でした。 ターミナル $ docker run <イメージ名> bundler -v Bundler version 2.3.7 どうやら、Bundlerのバージョンが2.3.7だとNameError: uninitialized constant Gem::Sourceが発生するようです。 また、2.3.8でも同様のエラーが発生しました。 2.3.6や2.3.9、2.3.10ではエラーは発生しませんでした。