技術

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

【Rails】productionモードでCSSの画像が表示されない

どうも中田です。 css内で画像を設定して、productionモードで動かすと …

no image

【Rails】RailsでFriendlyURLを設定する

こんばんは 例えばRailsでブログ記事ページのルーティングを設定するときは b …

no image

[wordpress]各固定ページに個別のCSSを読み込ませる

こんばんは wordpreddでオリジナルテーマを作成している時、各固定ページに …

no image

【Angular】component.htmlをprettierで整形する

こんにちは 今回はcomponent.htmlをprettierで整形する方法を …

no image

【ionic】リリースする!ちょっとその前に(version指定)

どうも、中田です。 ionic便利ですよね。 コマンド一つでマルチプラットフォー …