Skip to content

Instantly share code, notes, and snippets.

@takat0-h0rikosh1
Last active December 27, 2021 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takat0-h0rikosh1/add2cbe0c6010ed9928c6ca0482b20c0 to your computer and use it in GitHub Desktop.
Save takat0-h0rikosh1/add2cbe0c6010ed9928c6ca0482b20c0 to your computer and use it in GitHub Desktop.
MY_RAILS_NOTE
Railsの知見置き場

yarn install

npm i -g yarn

fix production.rb

config.assets.compile = true # false to true

precompile

bundle exec rails assets:precompile RAILS_ENV=production

本体が消えたときにAssociateされたモデルも消すには dependent: destroy を指定する。

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
end

削除系メソッドとその説明。

メソッド 説明 関連データ削除
destroy データを1件削除 true
destroy_all where()と組み合わせて複数件データを削除 true
delete データを1件削除 false
delete_all where()と組み合わせて複数件データを削除 false

使い方。

# destory系
User.find(3).destory
User.where(id: 5..6).destroy

# delete系
User.find(3).delete
User.where(id: 5..6).delete_all
https://qiita.com/Ryoga_aoym/items/741c57e266a9d811a2d4
  • tarbolinks が悪さをすることがあるのでそのへんを探ってみる
  • そもそも fullcalendar-rails は3年もメンテされていないので利用を控えたほうが良い旨をお伝え
  • simple-calendar のほうがまだまし
# 全User取得
User.all

# 先頭ユーザー取得
User.first

# 主キーで検索(複数指定可能
User.find(1)

# find_byで検索 主キー以外も指定できる
User.find_by(name: 'pepepe')
User.find_by(name: 'pepepe', id: 1)

# where句 条件に合致しなかった場合は空の配列を返す
User.where(email: 'test@example.com', name: 'pepepe1')
User.where(name: 'pepepe').or(User.where(name: 'tatata')) # OR
User.where(name: 'pepepe').where(name: 'tatata') # AND
User.where.not(name: 'pepepe') # NOT

N+1問題になる実装

posts = Posts.all
posts.each do |post|
  puts post.user.name
end

実行ログは下記の通り。
PostモデルからAssociateされたUserモデルを表示しようとするたび、SQLが発行される。

Posts Load (0.3ms) SELECT articles.* FROM posts
User Load (0.2ms) SELECT users.* FROM users WHERE users.id = 3 LIMIT 1
"taro"
User Load (0.3ms) SELECT users.* FROM users WHERE users.id = 3 LIMIT 1
"taro"
User Load (0.2ms) SELECT users.* FROM users WHERE users.id = 3 LIMIT 1
"taro"
User Load (0.2ms) SELECT users.* FROM users WHERE users.id = 3 LIMIT 1
"taro"
User Load (0.3ms) SELECT users.* FROM users WHERE users.id = 3 LIMIT 1
"taro"

includesを使った実装

posts = Posts.includes(:user)
posts.each do |post|
  puts post.user.name
end

実行ログは下記の通り。
AssociateされたUserモデルの情報を事前に読み込んでいるのでSQLが発行されない。

Post Load (0.6ms) SELECT posts.* FROM posts
User Load (0.5ms) SELECT users.* FROM users WHERE users.id = 3
"taro"
"taro"
"taro"
"taro"
"taro"
```rails
answers.joins(:element).where(:elements => {:kind => 6})
```
https://stackoverflow.com/questions/35246196/rails-how-to-access-child-model-attributes-in-where
https://stackoverflow.com/questions/10359728/no-such-column-when-column-exists

routes 確認方法

app.user_path

# コントローラーとアクションに対応するパスを確認できる(POST,PATCHとかのやつは見れない?)
app.url_for(controller: 'users', action: 'index')
=> "http://www.example.com/users"

# こういうこともできるらしい
user = User.first
app.url_for(user)
app.polymorphic_path(user)

# パスから逆引きもできる
Rails.application.routes.recognize_path('/users')
=> {:controller=>"users", :action=>"index"}

migration

# マイグレーション
rails db:migrate

# DBを完全に作り直す
rails db:migrate:reset

production で gem install が無視されてた

gem install し直しなおせば治るかも?

.bundle(もしくは.vendor???) 以下を一回削除して bundle install --without develop, test? だかをし直すのが手っ取り早いと思います。 → 治らず...

原因

.bundle/config に記載されている BUNDLE_WITHOUT に production が指定されていたので gem install されていなかった。

kill `cat tmp/pids/server.pid`
# edit.erb.html

<%= form_for @article do |f| %>

  <%= f.text.field :title %>

  <%= f.fields_for :images do |image| %>
    <%= attachment_image_tag image.object, :image, :fill, 100, 100 %> # 画像表示
    <%= image.file_field :content %>
    <%= image.hidden_field :id, value: image.object.id %> # 編集時にはidが必要
  <%= f.submit %>

<% end %>
# article.rb

class Article < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images, allow_destroy: true
end
# article_controller.rb

  def update
    @team = Article.find(params[:id])
    if @team.update(update_team_params)
      redirect_to root_path
    else
      render :edit
    end
  end
  
  def update_artcle_params
    params.require(:team).permit(:title, images_attributes: [:id, ...])
  end
https://stackoverflow.com/questions/32439814/can-i-configure-separate-s3-buckets-in-refile-initializer-for-different-function

refile の fill とか size とかはポンコツだから css でなんとかしろ

view の実装

<div class="img-container">
  <%= attachment_image_tag @recipe, :recipe_image, format:'jpeg' %>
</div>

css の実装

.img-container {
  width: 360px;
  height: 260px;
}
.img-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

Rails で Transaction をやる

ActiveRecord::Base.transaction do
  @user = User.find(params[:id])
  if @user.update(user_params)
    redirect_to user_path(@user.id), notice: 'Update user info successfully'
  else
    flash.now[:alert] = @user.errors.full_messages
    render :edit
  end
end
https://github.com/deivid-rodriguez/byebug

Controller の中断したいところで binding.pry とすればOK。 下記のような感じで使う。

[1] pry(#<HogeController>)> request.format
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment