技術

ActiveRecord::Relationのklassメソッドでmodelを取得できる。

投稿日:

こんにちは。コーテッグのこやまです。

モデルに対してallやwhereメソッドを使って返ってくるのは、
ActiveRecord::Relationのインスタンスですが、
元クラスを取得したいときってありますよね。

RailsのActiveRecord::Relationでは
.classではclassを取得できます。
.klassでmodelを取得できます。
.modelでもmodelを取得できます。

自分でも何言っているかわからないのでコードを見てみましょう。

hoges = Hoge.where(id: [1..10])

// .class(Objectクラスのインスタンスメソッド)
hoges.class
=> Hoge::ActiveRecord_Relation


// .klass(Active Record RelationのAttributes)
hoges.klass
=> Hoge(id: integer, fuga_id: integer, .....)
Returns the class of the target. belongs_to polymorphic overrides this to look at the polymorphic_type field on the owner.


// .model(Active Record RelationのAttributes)
hoges.model
=> Hoge(id: integer, fuga_id: integer, .....)

ということでした。.classはRubyで.klassはRailsって感じですかね。
私は普段は.modelを使っています。

-技術

執筆者:


comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

関連記事

no image

【Angular7】ファイルの指定をルート相対パスにする

こんにちは Angularで別ファイル(例えばcomponentからservic …

どうも中田です。 Rails5.2から config/credentials.y …

[Ionic]UnhandledPromiseRejectionWarning: CordovaError: Requirements check failed for JDK 1.8 or greater

こんにちわ。田中です。 参画しているプロジェクトで使っているのもあって、現在Io …

CentOS7でDocker内部からpingができない(外部通信できない)!

どうもなかたです CentOS7にDocker入れて、Docker内部から外に向 …

Webページまるごと画面キャプチャできるChromeの拡張機能「Full Page Screen Capture」

こんにちは。たなかです。 先日、チームのメンバーにスマホデザインのスクリーンショ …