• 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

例えばselect結果をinsertするような場合は効率面からActiveRecordを通さずそのままSQLを実行したい。select結果が数千件ある場合ARで素直に書くとそのまま数千回insert実行しなきゃならんので。

Railsでは基本ARで操作できるけど必要があればSQL書ける柔軟な所がある。 今回の場合ActiveRecord::Base::connection::executeを使用する。 Railsレシピブックで言うとP239の例。

   1  Class Entry < ActiveRecord::Base
   2    def self.select_insert_hogehoge
   3      sqlstr = "hogehoge"
   4      return connection.execute(sqlstr)
   5    end
   6  end

posted by Face ysakaki on Thu 28 Aug 2008 at 16:01

NetBeans6.1で「プロジェクト内を置換」を実行した場合。 コメント内を置換するとそれ以降のソースが吹っ飛ぶ。 日本語関係の問題なのか、コメント内だからいけないのかとか、そこまでは調べていない。

下記のコードで「# ・」みたいになってそれ以降のソースがなくなってしまう (苦笑)

   1        # ソート条件

posted by Face ysakaki on Mon 25 Aug 2008 at 09:21

チームで開発しているときに「俺が関係しているテーブルのfixtureだけloadしたいんだぜー」というときに使う。使い方は調べたけど結局使わなかった。

rake db:fixtures:load fixtures=fixture1,fixture2,fixture3,・・・

posted by Face ysakaki on Mon 25 Aug 2008 at 08:29

色々奥が深いと思った(not http://0xcc.net/misc/bad-knowhow.html 笑)

■前提:記事←関連テーブル→ユーザというモデル関係がある。

   1  # has_many :throughのパターン
   2  class Article< ActiveRecord::Base
   3    has_many :articles_users
   4    has_many :users, :through => :articles_users
   5  end
   6  
   7  class User < ActiveRecord::Base
   8    has_many :articles_users, :dependent => :destroy
   9    has_many :articles, :through => :articles_users
  10  end
  11  
  12  # 関連テーブルを実テーブルで持つ
  13  class ArticlesUsers < ActiveRecord::Base
  14    belongs_to :article
  15    belongs_to :user
  16  end

■関連テーブルの操作

あるユーザの関連をごそっと別の関連に切り替えたいような場合!

User.articles_users.destroy_allして作り直すという方法もあるが User.articles_users.replace()という便利なメソッドがある。

AWD第二版(AgileWebDevelopment)で言うとP308。 「○orders.replace(order1,...) この顧客に関連付けられた注文のセットを、新しいセットに置き換える。現在の子のセットと新しいセットの違いを検出し、それに応じてデータベースの変更を最適化する。」という奴。

   1   /ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb
   2  
   3        # Replace this collection with +other_array+
   4        # This will perform a diff and delete/add only records that have changed.
   5        def replace(other_array)
   6          other_array.each { |val| raise_on_type_mismatch(val) }
   7  
   8          load_target
   9          other   = other_array.size < 100 ? other_array : other_array.to_set
  10          current = @target.size < 100 ? @target : @target.to_set
  11  
  12          @owner.transaction do
  13            delete(@target.select { |v| !other.include?(v) })
  14            concat(other_array.select { |v| !current.include?(v) })
  15          end
  16        end
これは便利。

1.配列を放り込むだけ

「Replace this collection with +other_array+」ということで検索結果、あるいはセッションなどで生成した新しい関連の配列を放り込むだけで使える。

2.以前の関連との差分をチェックして差分だけ反映してくれる。

「This will perform a diff and delete/add only records that have changed.」ということで必要な差分だけチェックして必要なdelete/addをしてくれる。

ちなみにdeleteだと「Railsレシピブック」のP157「Entryオブジェクトobjectとの関連を削除する。Entryオブジェクトobjectの外部キー(blog_id)をNULLにし、関連を削除する。複数の参照元オブジェクトを同時に指定できる。」にある通り、関連テーブルの実レコードは削除されない(外部キーがNULLになるだけ)。関連テーブルにごみが残って気持ち悪い場合は上記モデルのように「:dependent => :destroy」を付けると物理的に削除される。

posted by Face ysakaki on Fri 22 Aug 2008 at 15:54

remote_functionではPost値を:withでいちいち指定する必要がある。 フィールドの数が多い場合は大変だ。

そういう場合、prototype.jsにForm.serialize('フォームのID')でフォームの値をname1=value1&name2=value2形式にしてくれる関数が便利である。

   1  <%= javascript_include_tag "prototype" %>
   2  <script language="JavaScript">
   3  function newArticle(){
   4      <%= remote_function(:url => {:action => :new},
   5                           :update => 'list',
   6                           :with => "Form.serialize('article')"
   7      ) %>
   8  }
   9  </script>
  10  

posted by Face ysakaki on Tue 19 Aug 2008 at 12:01

たとえばJavaScriptの都合などでactionがnewでもeditでもフォームタグのidが同じになって欲しいことがある。 そういう場合は:html=>{:name1=>'value1',:name2=>'value2'}でhtmlオプションを指定できる。

   1  <% remote_form_for(@article, :url => {:action => :update, :id => @article}, :update => 'list',:html=>{:id=> 'article'}) do |f| %>
   2  
   3    <%= render :partial=>f %>
   4  
   5    <p>
   6      <%= f.submit "保存" %>
   7    </p>
   8  <% end %>

posted by Face ysakaki on Tue 19 Aug 2008 at 11:56

サーバーを再起動したらmysqlが起動していなかった。 サービスとして登録するには以下。

   1  # chkconfig --list mysqld
   2  mysqld 0:off 1:off 2:off 3:off 4:off 5:off 6:off
   3  #chkconfig --level 345 mysqld on
   4  #chkconfig --list mysqld
   5  mysqld 0:off 1:off 2:off 3:on 4:on 5:on 6:off

posted by Face ysakaki on Tue 12 Aug 2008 at 17:22

begin~rescue~endで処理する。 例外のメッセージにパターンがある場合はex.messageが特定文言を含むかどうか調べて人間に優しいメッセージに変更する。

   1    def destroy
   2      @article = Article.find(params[:id])
   3      begin
   4        if @article.destroy
   5          flash[:notice] = '記事を削除しました。'
   6        end
   7      rescue => ex
   8        #「violates foreign key」は外部キーの参照エラー。関連テーブルが存在するため削除できないことを意味する。
   9        if ex.message=~/violates foreign key/
  10          flash[:notice] = '該当記事を参照しているデータがあるため削除できません'
  11        else
  12          #その他の例外
  13          flash[:notice] = ex.message
  14        end
  15      end
  16      redirect_to :action => 'index'
  17    end

posted by Face ysakaki on Tue 12 Aug 2008 at 12:01

railsのcheck_buttonタグで選択済(checked)にするには、最後に:checked=>'checked'を追加する。

   1  radio_button("myform","category",1, :checked=>'checked')

すると下記のようなHTMLが出力される。

   1  <input checked="checked" id="myform_category" name="myform[category]" type="radio" value="1" />

posted by Face ysakaki on Wed 6 Aug 2008 at 15:39

CMSで改行入力したものを出力時に
として出力するヘルパタグ。 application_helper.rbに追加する用。

   1  def hbr(str)
   2    str = html_escape(str)
   3    str.gsub(/\r\n|\r|\n/, "<br />")
   4  end

VIEW側では<%=hbr textarea_value %>のように使う。

posted by Face ysakaki on Tue 5 Aug 2008 at 15:15
Contents
RailsでDBクエリを直接発行する方法
NetBeansのバグ?コメント内を置換するとファイルが壊れる
railsで特定のfixtureだけloadする
Railsの多対多で関連テーブルの操作色々
Form.seriarizeでremote_functionの:withにフォームの値を設定する
remote_form_forでフォームタグのidを指定する
Linuxのchkconfigでサービスのランレベルを設定する方法
Rails(Ruby)で例外処理
railsのcheck_buttonタグで選択済(checked)にする
HTMLエスケープして改行をbrに変換
Comments
satoko: 私もGIMP入れてみたんですよ、で、同じ文字化け。 言語の優先順位を1.English、2:... '08-11
榊 祐介: >satokoさん コメントありがとうございます。 画像編集はGIMPを入れてみたのですがい... '08-11
satoko: しまったsubmitするの忘れてたのですが、昨日書いていたコメントです。^^ '08-11
satoko: あわあわ、私も今日までずっと困っていました。先ほど別のところでこの設定方法を学んだところです!... '08-11
榊 祐介: 検索したら自分のブログだった乙orz '08-11
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ