はじめに
railsでは標準のirbよりも高度なpryがコンソールツールとしてよく使われています。
そしてデバッグ時にpryまたはirbでモデル表示「[モデル名].allなど」をおこなうと表示があまり見やすくありません。
もう少し見やすくということでHirbでは表形式で表示してくれます。
pry + Hirb の導入
Gemfileの追記
プロジェクト直下にあるGemfileへpryとHirbのgemを記述します
pryはpry-railsのみで良いのですが、よく使われるその他pry関連gemも入れておきます。詳細はドキュメントを参照ください。
group :development, :test do gem 'hirb' # hirb gem 'hirb-unicode' # hirbの日本語対応用 gem 'pry-rails' # pryコンソール gem 'pry-doc' # メソッドを表示 gem 'pry-byebug' # デバッグを実施(Ruby 2.0以降で動作) gem 'pry-stack_explorer' # スタックをたどる end
※どちらもデバッグツールのためdevelopment,testとしておきます
インストール実行
$ bundle install
.pryrcファイルの追加
.pryrcファイルをプロジェクト直下に以下の内容で作成してください。
begin require 'hirb' rescue LoadError # Missing goodies, bummer end if defined? Hirb # Slightly dirty hack to fully support in-session Hirb.disable/enable toggling Hirb::View.instance_eval do def enable_output_method @output_method = true @old_print = Pry.config.print Pry.config.print = proc do |*args| Hirb::View.view_or_page_output(args[1]) || @old_print.call(*args) end end def disable_output_method Pry.config.print = @old_print @output_method = nil end end Hirb.enable end
内容はバージョンにより更新される場合があるので最新版は以下のサイトより確認ください。
https://github.com/pry/pry/wiki/FAQ#hirb
動作チェック
pryコンソールモードに入ります
$ rails c
pryコンソールモードでモデルの情報を表示します
pry(main)> User.all
※Userモデルの値を表示
実行結果として表形式で表示されるようになっていればOKです。
はじめに
modelのnewとbuildをネットで見ると濫用していて使い道がわからなかったので調べてみました。
new/buildについて
以下、ドキュメントよりbuildはnewのエイリアスと記載されていました。そのため機能的には全く同じようです。
参考:
newについて
http://railsdoc.com/references/new
buildについて
http://railsdoc.com/references/build
暗黙的な使い方の違いについて
どちらも同じということですが、やはり使い分けには暗黙のルール(コーディングルール)があるようです。
例えば、Postsテーブル(投稿用)とComments(投稿に対するコメント)の場合、カーディナリティは1:Nになります。
その場合にPostsにはnew、その子に当たるCommentsにはbuildという具合に関係性を表す場合に使い分けているようです。
modelクラスではPostsはhas_manyで:comments、Commentsはbelong_toで:postsという関係性です。
Posts[1]
Posts.new
Comments[N]
Comments.posts.build
はじめに
scaffoldコマンドを実行したあとに元に戻す方法として、作成したファイルを手動削除するか、gitなどのバージョン管理で元に戻すことができますが、destroyコマンドで戻せることを知ったのでメモしておきます。
generateコマンドの戻し方
rails generate controllerコマンドを元に戻す
controller自動作成の実行
$ rails generate controller [コントローラ名] [アクション名] ...
controller自動作成のキャンセル
$ rails destory controller [コントローラ名] [アクション名] ...
rails generate modelコマンドを元に戻す
model自動作成の実行
$ rails generate model [モデル名] [フィールド名:データ型] ...
model自動作成のキャンセル
$ rails destoroy model [モデル名]
rails generate scaffoldコマンドを元に戻す
scaffoldの実行
$ rails generate scaffold [モデル名] [フィールド名:データ型] ...
scaffoldのキャンセル
$ rails destoroy scaffold [モデル名]
DB::queryの戻り値をModel型で返す方法をメモ
データベースへクエリを投げる方法が多々あるが、副問い合わせなどを使用した複雑なSQLなどになるとSQLを直接書いた方が可読性を考えてもよい
※直接SQLを実行する場合にはエスケープ処理をは自動的に行われないため、手動でいれることが必要になる
select文(稀にupdate文も)に限って言うとSQL直接記述のほうが今後のカスタマイズなど考えてもトータル間違いない。この場合crudすべてをSQL直接記述にしたほうが統一していいが、便利なメソッドもあるので、適時使い分けるのがいい。
データベースへクエリを実行する方法
データベース処理を行う方法
1.DBクラスのDB::queryメソッドで直接SQLを記述してクエリを実行する
2.DBクラスのクエリビルダーメソッドを使用してクエリを実行する
3.orm/Modelクラスの静的メソッドを使用してクエリを実行する
「1.DBクラスのDB::queryメソッドで直接SQLを記述してクエリを実行する」を使う場合と「3.orm/Modelクラスの静的メソッドを使用してクエリを実行する」を使う場合だと戻り値の型が違う。戻り値に関しては「3.orm/Modelクラスの静的メソッドを使用してクエリを実行する」の場合にはorm/Modelが返り、modelに関わるメソッドを備えているためなにかと便利。
そのため、DB::queryをmodel型に変換する方法をメモ
※参考:http://docs.fuelphp.com/classes/database/usage.html
Orm/Modelを継承したModel_Userを用意
protected static $_properties = array( 'id', 'username', 'password', 'group', 'email', 'last_login', 'created_at', 'updated_at' );
「3.orm/Modelクラスの静的メソッドを使用してクエリを実行する」でusername,passwordに一致するレコードを取得
$users = Model_User::find( 'all', array('username' => $username,'password' => $password) );
array 2 => object(Model_User)[32] protected '_is_new' => boolean false protected '_frozen' => boolean false protected '_data' => array 'id' => string '2' (length=1) 'username' => string 'admin' (length=5) 'password' => string '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8' (length=40) 'group' => string '1' (length=1) 'email' => string 'test@hotmail.com' (length=16) 'last_login' => string '1' (length=1) 'created_at' => string '111111111' (length=9) 'updated_at' => string '1356073749' (length=10) protected '_original' => array 'id' => string '2' (length=1) 'username' => string 'admin' (length=5) 'password' => string '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8' (length=40) 'group' => string '1' (length=1) 'email' => string 'test@hotmail.com' (length=16) 'last_login' => string '1' (length=1) 'created_at' => string '111111111' (length=9) 'updated_at' => string '1356073749' (length=10) protected '_data_relations' => array empty protected '_original_relations' => array empty protected '_reset_relations' => array empty protected '_view' => null protected '_iterable' => array empty
「1.DBクラスのDB::queryメソッドで直接SQLを記述してクエリを実行する」でusername,passwordに一致するレコードを取得
「3.orm/Modelクラスの静的メソッドを使用してクエリを実行する」と同様に戻り値の型をMode_Userにするためにはas_objectメソッドでオブジェクト名を指定する必要がある。さらにas_arrayメソッドで配列へ変換することも同時に必要。これで実行すると同様の結果になる。
※bindメソッドでエスケープ処理を行っている
$users = DB::query( 'SELECT * FROM tb_users WHERE username = :username AND password = :password' ) ->bind('username', $username) ->bind('password' , $password) ->as_object('Model_User') ->execute() ->as_array();
array 0 => object(Model_User)[33] protected '_is_new' => boolean false protected '_frozen' => boolean false protected '_data' => array 'id' => string '2' (length=1) 'username' => string 'admin' (length=5) 'password' => string '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8' (length=40) 'group' => string '1' (length=1) 'email' => string 'test@hotmail.com' (length=16) 'last_login' => string '1' (length=1) 'created_at' => string '111111111' (length=9) 'updated_at' => string '1356073881' (length=10) protected '_original' => array 'id' => string '2' (length=1) 'username' => string 'admin' (length=5) 'password' => string '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8' (length=40) 'group' => string '1' (length=1) 'email' => string 'test@hotmail.com' (length=16) 'last_login' => string '1' (length=1) 'created_at' => string '111111111' (length=9) 'updated_at' => string '1356073881' (length=10) protected '_data_relations' => array empty protected '_original_relations' => array empty protected '_reset_relations' => array empty protected '_view' => null protected '_iterable' => array empty
戻り値の型がModel_Userになっている
coffee-break
Don't write code that useless.
1日5杯はコーヒー、カフェオレ飲みます。狭心症のため安静にします☆松本 雄貴
Kotlinでサービスリリース目指す!
iOSでチャットアプリ作成中。自然言語解析LSIを習得中
Mac / Android・iOS / Rails / Oracle
2017年 Lpic L2取得
2012年 Android技術者資格取得
2010年 OracleMasterGold10g取得
2008年 CCNAQiitaもたまに投稿
https://qiita.com/y-matsumoto東京近郊で常駐開発探してる方はこちらよりご連絡ください
SES企業でパートナー会社を探している企業様はこちらよりご連絡ください
スプリットカメラ iOS / Android
音声認識で聞いた日付から曜日当てアプリ Android
ソーシャルタイマー Android
カテゴリー
- ActiveRecord (2)
- Android (52)
- AndroidStudio (10)
- Ansible (1)
- AWS (1)
- Bash (18)
- Blog (7)
- BootStrap (1)
- CentOS (16)
- Chef (1)
- css (2)
- Eclipse (5)
- error (1)
- Facebook (2)
- Firebase (1)
- FuelPHP (16)
- Git (22)
- GitHub (3)
- Gradle (2)
- GraphAPI (1)
- Grunt (1)
- heroku (2)
- illustrator (1)
- iOS (17)
- Java (4)
- Jenkins (1)
- jQuery (3)
- Kotlin (2)
- Mac (22)
- nginx (1)
- Node.js (3)
- peco (1)
- php (5)
- Python (1)
- Rails (16)
- Ruby (11)
- shell (1)
- SNS (1)
- Swift (2)
- tmux (2)
- Vagrant (6)
- Vim (6)
- windows (2)
- WordPress (3)
- zsh (4)
- フリーランス (1)
- ライブラリ (1)
- 勉強会 (2)
- 宣伝 (1)
- 未分類 (2)
最近の投稿
- [MAC]HighSierraでgitプッシュエラー「Unable to negotiate with xxx.xxx.xxx.xxx port xx: no matching cipher found. Their offer: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se fatal: Could not read from remote repository.」
- [iOS]iOS11からFacebook,Twitter連携(シェアなど)廃止の対応方法
- [iOS]速報2017AppleSpecialEventのiOS11、iPhone8など発表内容について
- [iOS][Firebase]The default Firebase app has not yet been configured. Add `[FIRApp configure];
- [iOS]2017年9月リリースのiOS11で開発者が対応するべきこと
- 今人気の現金化サービスCASH(キャッシュ)を使ったレビュー
- [Pandoc][Mac]pandocでmarkdownからwordファイル作成
- [Android]映画サマーウォーズの聞いた日付(誕生日)から曜日当てをアプリ音声認識で簡単に実現
- [Android]起動しているActivityを取得するadb shell コマンド
- [Android][Kotlin]kotlin学習で参考になるサイト一覧
2023年12月 月 火 水 木 金 土 日 « 5月 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 アーカイブ
- 2018年5月
- 2017年9月
- 2017年8月
- 2017年7月
- 2017年6月
- 2017年5月
- 2017年2月
- 2017年1月
- 2016年12月
- 2016年7月
- 2016年6月
- 2016年1月
- 2015年12月
- 2015年11月
- 2015年10月
- 2015年9月
- 2015年8月
- 2015年7月
- 2015年6月
- 2015年5月
- 2015年4月
- 2015年3月
- 2015年2月
- 2015年1月
- 2014年12月
- 2014年11月
- 2014年6月
- 2014年5月
- 2014年4月
- 2014年3月
- 2014年2月
- 2014年1月
- 2013年12月
- 2013年11月
- 2013年9月
- 2013年8月
- 2013年7月
- 2013年6月
- 2013年5月
- 2013年4月
- 2013年3月
- 2013年2月
- 2013年1月
- 2012年12月
- 2012年10月
- 2012年5月
- 2010年6月
おすすめ備忘録
- [Ruby]putsとinspectとpメソッドについて
- [Rails]Rails4へ論理削除gemのparanoiaを導入する
- [Rails]generateコマンド(scaffold,conroller,modelなど)の実行(ファイル作成)を取り消す方法について
- [Rails][Ruby]エラー:Warning: You’re using Rubygems 1.8.23 with Spring. Upgrade to at least Rubygems 2.1.0 and run `gem pristine –all` for better startup performance.
- [Rails]MacにRails開発環境を構築(インストール)する
エントリ