はじめに みなさん、ActiveRecordの serialize や store は好きですか? 僕は 嫌い です。 serialize や store は原則として使わない方がみんな幸せになれると思っています。 なのでみなさんも serialize や store は使わないようにしてください。 以上! ・・・で終わったら意味がわからないと思うので、この件についてなぜダメなのかをちょっと詳しく掘り下げてみます。 そもそも serialize / store とは? serialize や store は ActiveRecord の機能の一つです。 text型のカラムに配列やハッシュなど、好きな形式のデータを放り込めます。 テーブルやカラムを追加しなくても自由にデータが保存できる 魔法のような機能 (注:皮肉)です。 サンプルコードを使ってこの機能を確認してみましょう。 以下の例では
Ruby on Rails 8.0.3 Module ActiveRecord::Aggregations::ClassMethods activerecord/lib/active_record/aggregations.rb Active Record Aggregations¶ ↑ Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like “Account [is] composed of Money [among other things]” or “Person [is] composed of [an]
In Rails 4.x, it is not possible to have destroy dependency on both sides of a bi-directional association between the two models as it would result in an infinite callback loop causing SystemStackError: stack level too deep. 1 2class User < ActiveRecord::Base 3 has_one :profile, dependent: :destroy 4end 5 6class Profile < ActiveRecord::Base 7 belongs_to :user, dependent: :destroy 8end 9 Copy 1 2>>
In Rails 4.x, when we save an ActiveRecord object then Rails automaticallyupdates fields updated_at or updated_on. >> user = User.new(name: 'John', email: 'john@example.com')>> user.save INSERT INTO "users" ("name", "created_at", "updated_at", "email") VALUES (?, ?, ?, ?) [["name", "John"], ["created_at", 2016-03-16 09:12:44 UTC], ["updated_at", 2016-03-16 09:12:44 UTC], ["email", "john@example.co
Let's look at a validation example in Rails 4.x. class User < ActiveRecord::Base validates :email, presence: trueend>> user = User.new>> user.valid?=> false>> user.errors.messages=> {:email=>["can't be blank"]}In this case, we do not get any information about the type of failed validationas ActiveModel#Errors only gives the attribute name and the translated errormessage. This works out well for no
Deleted articles cannot be recovered. Draft of this article would be also deleted. Are you sure you want to delete this article? db/schema.rbは何に使われるのか rake db:migrateなどをすると現在のスキーマが反映され、スキーマの確認などに便利なschema.rb。 ふと、1つのRailsアプリを分割して、複数のRailsアプリから同じDBを参照するようにしたくなったのだが、その際にどちらのRailsアプリにもdb/schema.rbを含める必要があるのか気になった。 db/schema.rbを削除してもアプリは動くのだが、 schema.rbには「It's strongly recommended that you check this f
This webpage was generated by the domain owner using Sedo Domain Parking. Disclaimer: Sedo maintains no relationship with third party advertisers. Reference to any specific service or trade mark is not controlled by Sedo nor does it constitute or imply its association, endorsement or recommendation.
環境: rails (4.1.6) activerecord (4.1.6) mysql2 (0.3.16) Rails4 というか Rails でカウンター用カラムをインクリメントする簡単な方法がないか調べてみた。 やりたいこと MySQL だったら以下のような SQL を発行したい。 update books set reviews_count = reviews_count + 1, updated_at = now() where id = ? カウンターのインクリメントと同時にソートのために更新日時も一緒に更新したい。 検証用環境の作成 $ bundle exec rails new counter_app -d mysql -T --skip-bundle $ cd counter_app $ bin/bundle install --path vendor/bundle モデ
RailsのChangeLogを読んでいたらkamipoさんの ActiveRecordへのコミットがRails5から使えるようになってるものがたくさんあったのでまとめてみました。 PostgreSQLでExpression IndexとOperator Classをサポート MySQLでPrepared statesmentsをサポート config/database.ymlでprepared_statements: trueとすると利用できるようになります。mysql2 0.4.4以降が導入されていないと使えないようです。 Schema dumperがcreate_tableブロックの中でindexを定義するようになった schema.rbのcreate_tableのブロック内でt.indexでインデックスが定義されるように変更されています。以前はcreate_tableのブロック外で
We sometimes need unique and random tokens in our web apps. Here is how wetypically build it. class User < ActiveRecord::Base before_create :set_access_token private def set_access_token self.access_token = generate_token end def generate_token loop do token = SecureRandom.hex(10) break token unless User.where(access_token: token).exists? end endendhas_secure_token in Rails 5Rails 5has added has_s
% rails c Loading development environment (Rails 4.0.0.beta1) > hoge = Hoge.new => #<Hoge id: nil, created_at: nil, updated_at: nil> > open('methods.txt', 'w'){ |file| > file.print(hoge.methods.join("\n")) > } => nil ! != !~ <=> == === =~ [] []= __id__ __send__ _attr_readonly _commit_callbacks _commit_callbacks= _commit_callbacks? _create_callbacks _create_callbacks= _create_callbacks? _destroy _d
Class methods (26) allow_unsafe_raw_sql (<= v6.1.7.7) allow_unsafe_raw_sql= (<= v6.1.7.7) application_record_class? asynchronous_queries_session asynchronous_queries_tracker configurations configurations= connected_to_stack connection_class connection_class= connection_class? connection_classes (<= v6.1.7.7) connection_class_for_self connection_handler connection_handler= connection_handlers (<= v
# File activerecord/lib/active_record/validations/absence.rb, line 20 def validates_absence_of(*attr_names) validates_with AbsenceValidator, _merge_attributes(attr_names) end Validates whether the associated object or objects are all valid. Works with any kind of association. class Book < ActiveRecord::Base has_many :pages belongs_to :library validates_associated :pages, :library end WARNING: This
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く