create_or_update 的なメソッドをRailsで使いたいとき

既に該当するモデルの値が存在していたら update で値を更新して、まだ存在しない場合は create で新しくモデルのインスタンスを作成したい時ありませんか? 少なくとも自分にはありましたし、検索でここに辿り着いたあなたもきっとあると思います。 Railsならきっと簡単な方法があると思ったので調べてみたらありました。 やり方。 こんな感じでOK。 my_class = ClassName.find_or_initialize_by_name(name) my_class.update_attributes( :street_address => self.street_address, :city_name => self.city_name, :federalid => self.federalid, :state_prov_id => self.state_prov_id, :zip_code => self.zip_code ) 注意点 ちなみに create_or_update は ActiveRecord::Callbacks の private 関数として用意されてるご様子。 [create_or_update (ActiveRecord::Callbacks) – APIdock][1] 参考 [ruby – create_or_update method in rails – Stack Overflow][2]

2013-12-15 · 鉄

respond_to を ブロックを使わずに書く。

Ajaxの処理をRailsでするときはControllerに respond_to do |format| format.js end と書いてたんですが、いちいちブロック引数に format を使って処理するのは無駄な気がしたので一行で書ける方法を調べてみた。 解決策 respond_to :js でOKでした。 respond_to :html, :js な書き方もOKなようです。 参考 [respond_to (ActionController::MimeResponds::InstanceMethods) – APIdock][1]

2013-12-15 · 鉄

Gemfileを開いてたらsmart-compileで`bundle install`を実行する

開いてるファイルをそのまま実行できるsmart-compileでGemfileを開いてたらbundle installを実行したかったのでやり方を調べてみました。 設定方法 どうやらsmart compile は自動的にコマンドの実行ディレクトリをファイルがある場所に移動してくれるようなので単純に Gemfileというファイル名とbundle installのコマンドを他のファイルと同じように紐付ければOKのようです。 (global-set-key (kbd "C-c C-x") 'smart-compile) (setq smart-compile-alist (append '(("\\.rb$" . "ruby %f")) '(("\\.php$" . "php %f")) '(("\Gemfile$" . "bundle install")) smart-compile-alist)) もちろん ruby や php を使ってなかったら該当行は必要ありません。 使い方 これで Gemfile を開いて C-c C-x するとこんな風に bundle install が実行されます。 -*- mode: compilation; default-directory: "~/dev/foo/" -*- Compilation started at Sun Dec 15 16:29:42 bundle install Using rake (10.1.0) Using i18n (0.6.9) from git://github.com/svenfuchs/i18n.git (at master) Using minitest (4.7.5) Using multi_json (1.8.2) Using atomic (1.1.14) Using thread_safe (0.1.3) Using tzinfo (0.3.38) Using activesupport (4.0.0) Using builder (3.1.4) Using erubis (2.7.0) Using rack (1.5.2) Using rack-test (0.6.2) Using actionpack (4.0.0) Using mime-types (1.25.1) Using polyglot (0.3.3) Using treetop (1.4.15) Using mail (2.5.4) Using actionmailer (4.0.0) Using activemodel (4.0.0) Using activerecord-deprecated_finders (1.0.3) Using arel (4.0.1) Using activerecord (4.0.0) Using sass (3.2.12) Using bootstrap-sass (3.0.3.0) Using will_paginate (3.0.5) Using bootstrap-will_paginate (0.0.10) Using mini_portile (0.5.2) Using nokogiri (1.6.0) Using xpath (2.0.0) Using capybara (2.2.0) Using timers (1.1.0) Using celluloid (0.15.2) Using ffi (1.9.3) Using childprocess (0.3.9) Using coderay (1.1.0) Using coffee-script-source (1.6.3) Using execjs (2.0.2) Using coffee-script (2.2.0) Using thor (0.18.1) Using railties (4.0.0) Using coffee-rails (4.0.1) Using diff-lcs (1.2.5) Using factory_girl (4.3.0) Using factory_girl_rails (4.3.0) Using faker (1.2.0) Using formatador (0.2.4) Using friendly_id (5.0.2) Using rb-fsevent (0.9.3) Using rb-inotify (0.9.2) Using listen (2.4.0) Using lumberjack (1.0.4) Using method_source (0.8.2) Using slop (3.4.7) Using pry (0.9.12.4) Using guard (2.2.4) Using rspec-core (2.14.7) Using rspec-expectations (2.14.4) Using rspec-mocks (2.14.4) Using rspec (2.14.1) Using guard-rspec (4.2.0) Using spork (1.0.0rc4) Using guard-spork (1.5.1) Using hike (1.2.3) Using jbuilder (1.5.3) Using jquery-rails (3.0.4) Using json (1.8.1) Using bundler (1.3.5) Using tilt (1.4.1) Using sprockets (2.10.1) Using sprockets-rails (2.0.1) Using rails (4.0.0) Using rdoc (3.12.2) Using rspec-rails (2.14.0) Using sass-rails (4.0.1) Using sdoc (0.3.20) Using spork-rails (4.0.0) Using sqlite3 (1.3.8) Using turbolinks (2.0.0) Using uglifier (2.3.3) Your bundle is complete! It was installed into ./vendor/bundle Compilation finished at Sun Dec 15 16:29:45

2013-12-15 · 鉄

Railsのカラム名の語頭に数字を使ってはいけない

Railsの学習がてらに2chもどきをつくろうと思って `rails new 2ch` してみるとエラーになる。これはいいんだけど、`rails generate Model 2ch` ってエラーを吐かないのに実際は使えないので修正がめんどくさくなるので気をつけましょう。

2013-12-14 · 鉄

[deprecated] RailsでI18n.enforce_available_locales とエラーが出る時の対処法

Railsでこんなdeprecatedの警告が出てきたので対処方法を調べた。 [deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message. 対策 config.i18n.enforce_available_locales = true でOK, `locale validation` をきちんとするなら true、どうでも良いならfalseらしい。よくわかんない。 参考 [ruby – Rails I18n validation deprecation warning – Stack Overflow][1]

2013-12-13 · 鉄

link_to で内部にタグがあったりする時はブロックを使いましょう

Zurb-Foundation とか Twitter bootstrap を使ってると、アイコンをリンク内に含めたくなったりしますよね。こんな感じに [crayon lang=“html”] Reload [/crayon] でもこれをそのまま `link_to` で囲んで [crayon lang=“html”] <%= link_to “ Reload”,“http://example.com/reload" %> [/crayon] とすると``タグが HTML エスケープされて悲しい事態になるんです。 対策 なのでそういう時は `link_to` さんはブロックが取れるのでブロックを使って処理しましょう。ブロックの返り値がリンクのテキストになります。 [crayon lang=“html”] <%= link_to “http://example.com/reload", class: ‘reload’ do %> Reload <% end %> [/crayon] ちなみに `button_to` も同じような関数なのでこういう風にかけます。 [crayon lang=“html”] <%= button_to “”, class: ‘small radius’ do %> Reload <% end %> [/crayon] これ知らない時に必死に HTML エスケープされないために何をすればよいのかを探しまくったのは今では良い思い出でもなんでもありません。時間返せ。 参考 [ruby on rails – link_to in helper with block – Stack Overflow][1] ...

2013-12-11 · 鉄

既に存在するindexにunique制限をかけるmigrationの書き方。

そのまま unique 条件付の index を追加しようとするとエラーになるので まず既にある index を削除してから追加しましょう。 [crayon title=“db/migrate/add_unique_constraint.rb”] def change remove_index :editabilities, [:user_id, :list_id] add_index :editabilities, [:user_id, :list_id], unique: true end [/crayon] 参考 [ruby on rails – How to add unique constraint to already existing index by migration – Stack Overflow][1]

2013-12-09 · 鉄

RailsでModelが不規則名詞だった場合のControllerの命名規則

Rails の Model は常に単数名詞、そして Controller はその名詞の複数形という規則がありますが、Model が”Child"などの不規則変化名詞だった時に Controller 名はChildren なのか、Childs なのかがわからなかったので調べました。 答え プログラム的には当然簡単に処理できる Childs だと思ったけども実際はちゃんと不規則変化にも対応してるらしく Children が正解です。 その他の不規則名詞 他の不規則名詞は https://github.com/rails/rails/blob/4-0-0/activesupport/lib/active_support/inflections.rb に載っているんですが、 inflect.irregular('person', 'people') inflect.irregular('man', 'men') inflect.irregular('child', 'children') inflect.irregular('sex', 'sexes') inflect.irregular('move', 'moves') inflect.irregular('cow', 'kine') inflect.irregular('zombie', 'zombies') zombie って不規則名詞なの…? cow→kine の変化はそもそも英単語がわかりませんでした、、 Zombie が不規則名詞の理由 ([2013/12/14] 追記) 単数形から複数形への変化は規則通りですが、複数形から単数形への変化 zombies -> zombie が不規則で、規則通り変化させてしまうと zombies -> zomby になってしまうから不規則名詞らしいです。英語は難しいですね。 情報元 [Model and Controller's naming rule for irregular noun in Rails – Stack Overflow][1]

2013-05-21 · 鉄

Railsで新規プロジェクトを作ろうとすると`expand_path’: non-absolute homeというエラーが出る

rails new hoge とすると `expand_path': non-absolute home というエラーが出てしまって「Windowsだしなあ。」と諦めかけてたけど、このhomeというのは環境変数のHOMEのことらしく、確かにcygwinを使う時のためにHOMEに /cygdrive/ から始まる値を入れてたのを思い出したので環境変数 HOME を削除してみたら動いた。 ちなみに irb もHOMEに入ってる値によっては動かないらしい。 参考 `expand_path': non-absolute home http://devnet.jetbrains.com/thread/437313

2013-05-01 · 鉄

JqueryとHTML5でajaxなファイルのアップロード

画面遷移無しでファイルのアップロードしようと思ったらiframeを使った技とかややこしい情報が色々出てきて、なかなかやりたいことに辿りつけなかったのでメモ。 やりたい事と条件 ・ajaxなテキストファイルのアップロード ・テキストをRubyで編集して返す ・画面遷移せずに結果を表示 ・IEは諦める。 必要最低限のコード まずHTMLを用意 ajaxupload.html ` <script type="text/javascript" src="ajaxupload.js" charset="utf8"></script><br> ` つぎにjavascript ajaxupload.js ` $(function(){ $("#upload").click(function(){ var file = $("#file")[0].files[0]; var reader = new FileReader(); reader.readAsText(file, 'UTF-8'); reader.onload = showFile; }); function showFile(event) { $.ajax({ type: "POST", url: "ajaxupload.rb", data: { filedata:event.target.result} }).done(function(msg) { $("#output").html(msg); }); } }); ` んで何か処理をするRubyのスクリプト。ここではファイルの中身をそのまま返してるだけ。(パス名は適宜変更してください。) ajaxupload.rb ` #!P:\Dropbox\bin\RailsPortable\App\Rails\bin\ruby.exe require "cgi" cgi = CGI.new print "Content-Type: text/html\n\n" print cgi['filedata'][0] ` デモ サンプルを置いておきます。(さくらのレンタルサーバーはRubyの拡張子がrbではなくcgiじゃなくと動かなかったのでファイル名を変えています。 ...

2013-02-27 · 鉄