並び順

ブックマーク数

期間指定

  • から
  • まで

121 - 150 件 / 150件

新着順 人気順

activerecordの検索結果121 - 150 件 / 150件

  • [Rails] has_oneで最新のレコードを取得できるようにしてeager_loadしたい

    1:N な関係でN個の中で最新のレコードだけ欲しい、っていうケースで has_manyなrelationのfirstを取得していくとN+1になりまくってつらいので has_oneで取得できるようにしてeager_loadする方法を調査したメモ 環境 OS: Ubuntu 20.04 Ruby: 3.0.2 Rails: 6.1.4.1 RDB: Postgres 13 薄いプロジェクトを作る FROM ruby:3.0.2-alpine3.12 as ruby ## Development FROM ruby AS dev ENV BUNDLE_FORCE_RUBY_PLATFORM=1 \ CFLAGS="-Wno-cast-function-type" RUN apk update \ && apk add --no-cache \ gcc \ g++ \ libc-dev \ lin

      [Rails] has_oneで最新のレコードを取得できるようにしてeager_loadしたい
    • Rails: Active Recordモデルのカラムを安全に削除する(翻訳)|TechRacho by BPS株式会社

      概要 元サイトの許諾を得て翻訳・公開いたします。 英語記事: Safely Remove a Column from an Active Record Model - Andy Croll 原文公開日: 2022/11/14 著者: Andy Croll 参考: Rails API ignored_columns= -- ActiveRecord::ModelSchema::ClassMethods 既存のActive Recordモデルに新しいカラムを追加してデプロイするのは、多くの場合問題なくできます。通常は、最初のデプロイでマイグレーションを実行し、それが終わってから、次にデータベースに追加されたカラムを利用する新しいコードをリリースするという手順になります。 しかし、カラムを削除する場合は問題が起きやすい傾向があります。Railsアプリケーションを起動すると、Active Reco

        Rails: Active Recordモデルのカラムを安全に削除する(翻訳)|TechRacho by BPS株式会社
      • 【Ruby On Rails】DBに一意性を与えるユニーク制約(unique)の正しい記述場所 - Qiita

        備忘録です。 ユニーク制約とは 一意性制約のことです。DBにおいてデータを追加や更新する際の制約。カラムに独自性を与えます。 例えば、ユニーク制約を適用することで、ユーザーが新規登録をする際に、既に登録されているemailアドレスと同じアドレスで登録しようとした場合にエラーを返すことができます。 uniqueの書き方 add_index :テーブル名, [:カラム名1, :カラム名2, :カラム名3, ...(続く)], unique: true

          【Ruby On Rails】DBに一意性を与えるユニーク制約(unique)の正しい記述場所 - Qiita
        • 令和の時代、hirbに変わるツールはあるのか問題 - すがブロ

          表形式の方がパッとみたときに分かりやすい反面、カラムが多いと表形式じゃない方が見やすいとかもあるのでケースバイケースなのですが、まあ敢えて剥がすほどでもないかなと思って使い続けて数年。 開発が活発ではないので、そろそろ次世代的なものが出てきているのか、あるいは人類は表形式じゃなくてもやっていけるのか。 hirb is 何 こんな感じに表示されるActiveRecordのオブジェクトに対して irb(main):002:0> Blog.all Blog Load (0.4ms) SELECT "blogs".* FROM "blogs" LIMIT ? [["LIMIT", 11]] => #<ActiveRecord::Relation [#<Blog id: 1, title: "cool title", body: "cool text", created_at: "2019-10-0

            令和の時代、hirbに変わるツールはあるのか問題 - すがブロ
          • Rails: 私の好きなコード(5)永続化とロジックを絶妙にブレンドするActive Record(翻訳)|TechRacho by BPS株式会社

            概要 原著者の許諾を得て翻訳・公開いたします。 英語記事: Code I like (V): Active Record, nice and blended 原文公開日: 2022/12/19 原著者: Jorge Manrubia -- 37signalsのエンジニアです 日本語タイトルは内容に即したものにしました。なお、以下の『素のRailsは十分に豊かである(翻訳)』記事は『私の好きなコード』シリーズの(4)に含まれました。 素のRailsは十分に豊かである(翻訳) 本記事は37signals dev blogで最初に公開されました リレーショナルデータベース内でのオブジェクトの永続化は、複雑な問題です。かれこれ20年ほど前、この問題は究極の直交性問題のように思われていました。すなわち、永続化を抽象化することで、プログラマーが永続化を気にしなくてよいようにするというものです。それから

              Rails: 私の好きなコード(5)永続化とロジックを絶妙にブレンドするActive Record(翻訳)|TechRacho by BPS株式会社
            • UUID Primary Key in Rails 6 with PostgreSQL and ActiveRecord

              UUID Primary Key in Rails 6 with PostgreSQL and Active Record Updated Mar 6, 2021 8 minute read UUID also known as GUID is an alternative primary key type for SQL databases. It offers some non-obvious advantages compared to standard integer-based keys. Rails 6 release fresh out of beta introduces a new feature in ActiveRecord that makes working with UUID primary keys more straightforward. In this

                UUID Primary Key in Rails 6 with PostgreSQL and ActiveRecord
              • Fetching millions of rows from PostgreSQL with Rails

                Let’s say you have a simple Rails application, and you want to process a large quantity of rows from a PostgreSQL instance. For instance, you want to iterate over every post the user has, so you may do something like this: Post.where(user_id: 16) ==> SELECT "posts".* FROM "posts" where "posts"."user_id" = 16This SQL query might take anything from some milliseconds to a couple of seconds on a regul

                  Fetching millions of rows from PostgreSQL with Rails
                • RailsのActiveRecordのAutosaveAssociationのコードリーディング - Rails Webook

                  RailsのActiveRecordのautosave機能についてソースコードリーディングをしました。 ドキュメント ActiveRecord::AutosaveAssociation ソースコード ActiveRecord::NestedAttributes - Tag 5.2.1 (18/8/8) Autosaveは、親モデルが保存された時に、関連するモデルも一緒に作成/更新する機能を提供します。 また、関連するモデルでmark_for_destricutionメソッドを実行し、削除フラグを立てることで、親モデルを保存時に関連レコードを削除することもできます。 これらのレコードの操作はトランザクション内で実行されるのでDBでデータ不整合が発生しません。 1. Autosave機能のサンプルコード 2. Autosaveでのメソッドやコールバックを定義している箇所 3. Autosave

                    RailsのActiveRecordのAutosaveAssociationのコードリーディング - Rails Webook
                  • Rails 7 adds the ability to schedule the query on the background thread pool

                    Rails 7 adds the ability to schedule the query on the background thread pool Mar 31, 2021 Often there need to be multiple database queries executed in the controller like, @genres = Genre.all @videos = Video.order(published_at: :desc) These queries get executed sequentially which in most cases isn’t a big deal. However, as our database grows in size, response times get longer and longer. A large p

                      Rails 7 adds the ability to schedule the query on the background thread pool
                    • ActiveRecord Scoped Association - ohbarye

                      Author.eager_load(:published_articles).where(article: { published: true })

                        ActiveRecord Scoped Association - ohbarye
                      • RailsのActiveRecordのcount、length、sizeメソッドの違い - Qiita

                        はじめに いよいよダットのターンです!たまにはRailsについて書かずHTMLかJavascriptばかりの記事を投稿したので今回はRailsのメソッドについて説明させていただきます。 開発者としてはこれらのメソッドを触ったことがあるはずですね。風通はこの三つの中に勝手に選んでどっちでも使って無事で計算されるので大丈夫と思いましたが、実はそうでしょうか?実際は場合によって返った結果も変わって実行する時間も異なる可能性があります。さっそくですが、始めましょう! 概要 この記事はこれらのメソッドがRubyに使われる時を気にしないでActiveRecordに使用する時だけ中心してください。結局、アソシエーションの中に幾つのレコードがあるか教えてくれますが、内部の処理がちょっと違います。 例えば、このモーデルとリレーションがあります。

                          RailsのActiveRecordのcount、length、sizeメソッドの違い - Qiita
                        • GitHub - kirillshevch/query_track: Find time-consuming database queries for ActiveRecord-based Rails Apps

                          You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

                            GitHub - kirillshevch/query_track: Find time-consuming database queries for ActiveRecord-based Rails Apps
                          • ActiveRecord::QueryMethodsのselectメソッドについて深掘りしてみた|TechRacho by BPS株式会社

                            こんにちは。BPSに入社してちょうど1年になりましたshin1rokです。 入社時に目標にしていた「TechRachoに技術系の記事を投稿する」を果たすべく、ActiveRecord::QueryMethodsのselectメソッドを深掘りしてみます。 API: ActiveRecord::QueryMethods - select 環境 Ruby: 2.6.3 Rails: 5.2.3 ローカルにRailsを読むためだけの小さいアプリを作り、RubyMineのコードジャンプとブレークポイントを駆使して探索しました。 そもそも(および深掘りの視点) selectメソッドはこのようにModelを拡張する形でAttribute(?)を追加することができます。 ※アソシエーションはUser has_many posts irb(main):014:0> user = User.joins(:po

                              ActiveRecord::QueryMethodsのselectメソッドについて深掘りしてみた|TechRacho by BPS株式会社
                            • GitHub - planetscale/fast_page: Blazing fast pagination for ActiveRecord with deferred joins ⚡️

                              You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert

                                GitHub - planetscale/fast_page: Blazing fast pagination for ActiveRecord with deferred joins ⚡️
                              • Rails で結合先のテーブルで条件つけたいけど結合元のレコードは全部欲しいってときは Scoped Association

                                プレーヤーがいないチーム C も一覧に表示されているのがポイントです。 以上の設定が、「結合先のプレーヤーテーブルにおいて論理削除されていないという条件をつけたいけど、チームのレコードは全部欲しい」という状況になっているのがお分かりいただけるでしょうか。 どうクエリメソッドを書けばよいか? まずパッと思いつくもの 例えばこんなのはどうでしょうかね。 Team.eager_load(:players).where(players: {deleted: false}) すると以下のようなSQLが発行されます。 SELECT "teams"."id" AS t0_r0, "teams"."name" AS t0_r1, "teams"."created_at" AS t0_r2, "teams"."updated_at" AS t0_r3, "players"."id" AS t1_r0, "p

                                  Rails で結合先のテーブルで条件つけたいけど結合元のレコードは全部欲しいってときは Scoped Association
                                • https://longliveruby.com/articles/active-record-counting-records

                                    https://longliveruby.com/articles/active-record-counting-records
                                  • Rails 6.1: CHECK制約のサポートをマイグレーションに追加(翻訳)|TechRacho by BPS株式会社

                                    概要 原著者の許諾を得て翻訳・公開いたします。 英語記事: Rails 6.1 adds support for check constraints to database migrations | Saeloun Blog 原文公開日: 2021/01/08 著者: Dhiraj Mishra サイト: Saeloun Blog | Ruby on Rails Consulting Company based in San Francisco and Boston | Page 1 | Saeloun Blog なお、該当のAPIドキュメントは以下です。 add_check_constraint -- ActiveRecord::ConnectionAdapters::SchemaStatements check_constraint -- ActiveRecord::Connectio

                                      Rails 6.1: CHECK制約のサポートをマイグレーションに追加(翻訳)|TechRacho by BPS株式会社
                                    • Rails 7.1: ActiveRecord::Baseにnormalizesが追加された(翻訳)|TechRacho by BPS株式会社

                                      2023.06.06 Rails 7.1: ActiveRecord::Baseにnormalizesが追加された(翻訳) Rails 7.1: ActiveRecord::Baseにnormalizesが追加された(翻訳) Rails 7.1で、Active Recordの属性値の正規化(normalization)を宣言するメソッドが新たに追加されました。これは、ユーザー入力のサニタイズ、書式の統一、外部由来のデータのクリーンアップで特に有用です。 Rails 7.1より前は、以下のようにbefore_saveコールバックで属性を正規化できます。 model User < ApplicationRecord before_save :downcase_email, if :email_present? private def email_present? email.present?

                                        Rails 7.1: ActiveRecord::Baseにnormalizesが追加された(翻訳)|TechRacho by BPS株式会社
                                      • Rails 5に入ったDB破壊系taskの防止処理について

                                        小ネタ。 Rails 5から、production environmentでのDB破壊系のtaskの実行を防止する仕組みが入りました。 例えば、production environmentでdb:dropを実行しようとすると、下記のようなエラー(ActiveRecord::ProtectedEnvironmentError)が発生します。 $ RAILS_ENV=production ./bin/rails db:drop rails aborted! ActiveRecord::ProtectedEnvironmentError: You are attempting to run a destructive action against your 'production' database If you are sure you want to continue, run the sa

                                          Rails 5に入ったDB破壊系taskの防止処理について
                                        • Storing Large JSON in PostgreSQL with Rails: Efficient Techniques

                                          If you store large objects in the database (such as JSON), for example, data for big reports, then this can take up a lot of space. To reduce the size of data, you can compress and store in binary form. PostgreSQL has a bytea field type for storing such data. You can add bytea column in Rails using migration add_column :reports, :data, :binary For binary field operations, you can use the Rails Att

                                            Storing Large JSON in PostgreSQL with Rails: Efficient Techniques
                                          • How to Avoid Race Conditions in Rails

                                            Race conditions are hard to debug—especially when you don't know it's a race condition! This article looks at some common race conditions and the best solutions for handling each one. When two users read and update a database record at the same time, you might run into critical problems that are undesirable. Let's say that for some reason, a customer clicks the pay button on the checkout page of a

                                              How to Avoid Race Conditions in Rails
                                            • GitHub - Envek/after_commit_everywhere: Use ActiveRecord transactional callbacks outside of models, literally everywhere in your application.

                                              You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert

                                                GitHub - Envek/after_commit_everywhere: Use ActiveRecord transactional callbacks outside of models, literally everywhere in your application.
                                              • Ruby on Rails 6.0.4 における Active Record の複数 DB の仕組み - Qiita

                                                今携わっている Rails 6.0 のプロジェクトで複数 DB に移行する際に、すんなりいかず実装を深く追うことになった。 その際に得た Active Record のコネクションハンドラーまわりについてのメモを残そうと思う。 なお、このエントリは Ruby on Rails 6.0.4 について調べたものであり、6.1 の新機能であるシャーディングなどについては対象外なので注意。 Ruby on Rails 6.0 における複数 DB の概要 従来、Ruby on Rails は 5.2 まで複数 DB への接続をサポートしておらず、Octopus や SwitchPoint のような gem を導入する必要があった。 しかし 6.0 から複数 DB サポートが入り、別途 gem をインストールすることなく複数の DB にアクセスできるようになった。 default: &default

                                                  Ruby on Rails 6.0.4 における Active Record の複数 DB の仕組み - Qiita
                                                • [Rails] self.abstract_class = true の意味と挙動

                                                  ActiveRecord::Base を継承したクラスをモデルとして作成すると、Rails はそのクラス名に対応したデータベースのテーブルを自動的に探そうとします。対応するデータベースのテーブルを用意しない場合は、self.abstract_class = true を書く必要があります。ActiveRecord::Base を継承したクラスを作成し、さらにそのクラスを継承させたい場合に self.abstract_class = true が書かれるようです。 実際に Rails 5.0.1 にて検証しました。例えば、app/models 以下に ActiveRecord::Base を継承したクラス Animal を作ります。そしてクラス Animal を継承したクラス Dog を作ります。そしてデータベースには dogs というテーブルを作成します。 app/models/anima

                                                    [Rails] self.abstract_class = true の意味と挙動
                                                  • Let's get started with Ruby && Rails Tips

                                                    【オフライン開催】Omotesando.rb #96 https://omotesandorb.connpass.com/event/313860/

                                                      Let's get started with Ruby && Rails Tips
                                                    • Sharing Query Logic Within ActiveRecord Models

                                                      I was recently working on an application in which we had a class method / scope used to return a specific set of users. This was fine and good until we found ourselves needing to capture the same logic at the instance level. Ideally, I was hoping to be able to avoid duplicating the logic, and simultaneously keep things efficient. Users in our application can be configured to receive alerts. We hav

                                                        Sharing Query Logic Within ActiveRecord Models
                                                      • RailsでMySQLを使う時にuuidにデフォルト値を入れたい - その辺にいるWebエンジニアの備忘録

                                                        こんにちは!kossyです! さて、今回はRailsでMySQLを使う時にuuidにデフォルト値を入れる方法についてブログに残してみたいと思います。 環境 Ruby 2.6.6 Rails 6.0.3 MySQL 5.7系 moduleの作成 PostgreSQLの場合だとuuid型のカラムが存在しているのですが、MySQLの場合はありません。 # PostgreSQLの場合だとt.uuidでuuid型のカラムが用意されていて、uuid_generate_v4()関数でデフォルト値を設定できる t.uuid :uuid, null: false, default: 'uuid_generate_v4()' このため、独自でuuidを自動挿入する仕組みを整える必要があります。 コードを晒すと以下のような実装になります。 # uuid生成のモジュール # このモジュールをuuidを自動挿入した

                                                          RailsでMySQLを使う時にuuidにデフォルト値を入れたい - その辺にいるWebエンジニアの備忘録
                                                        • Rails 7: 関連付けのあるレコードを取れる'associated'クエリメソッドが追加(翻訳)|TechRacho by BPS株式会社

                                                          概要 原著者の許諾を得て翻訳・公開いたします。 英語記事: Rails 7 adds query method associated to check for the association presence | Saeloun Blog 原文公開日: 2021/02/15 著者: Romil Mehta サイト: Saeloun Blog | Ruby on Rails Consulting Company based in San Francisco and Boston 日本語タイトルは内容に即したものにしました。以下の関連記事もどうぞ。 週刊Railsウォッチ20201208: 新機能: where.associatedで関連付けにデータが存在するかどうかをチェックできるようになった 追記(2021/09/27): 当初の原文はRails 6.1が対象となっていましたが、Rails

                                                            Rails 7: 関連付けのあるレコードを取れる'associated'クエリメソッドが追加(翻訳)|TechRacho by BPS株式会社
                                                          • Rails 6.1 adds delegated_type to ActiveRecord

                                                            Rails 6.1 adds delegated_type to ActiveRecord which makes it easier for models to share responsibilities. Before Rails 6.1 Let's say we are building software to manage the inventory of an automobile company. It produces 2 types of vehicles, Car and Motorcycle. Both have name and mileage attributes. Let's look into at least 2 different solutions to design this system. <br/> Single Table Inheritance

                                                              Rails 6.1 adds delegated_type to ActiveRecord
                                                            • Simple Way to Encrypt Data in Rails without Gem

                                                              Storing sensitive data in plaintext can seriously harm your internet business if an attacker gets hold of the database. Encrypting data is also a GDPR friendly best practice. In this tutorial I will describe a simple way to securely encrypt, store, and decrypt data using built in Ruby on Rails helpers instead of external dependencies. Avoid heavy Gem dependencies attr_encrypted gem is a popular to

                                                                Simple Way to Encrypt Data in Rails without Gem