<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Groove Labo &#187; Ruby on Rails</title>
	<atom:link href="http://labo.opengroove.com/blog/category/ruby-on-rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://labo.opengroove.com/blog</link>
	<description>株式会社オープングルーヴの開発者のブログ</description>
	<lastBuildDate>Tue, 28 Sep 2010 06:09:57 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Railsのdatetime_selectの保存の仕組みを調べてみる</title>
		<link>http://labo.opengroove.com/blog/2010/09/28/rails%e3%81%aedatetime_select%e3%81%ae%e4%bf%9d%e5%ad%98%e3%81%ae%e4%bb%95%e7%b5%84%e3%81%bf%e3%82%92%e8%aa%bf%e3%81%b9%e3%81%a6%e3%81%bf%e3%82%8b/</link>
		<comments>http://labo.opengroove.com/blog/2010/09/28/rails%e3%81%aedatetime_select%e3%81%ae%e4%bf%9d%e5%ad%98%e3%81%ae%e4%bb%95%e7%b5%84%e3%81%bf%e3%82%92%e8%aa%bf%e3%81%b9%e3%81%a6%e3%81%bf%e3%82%8b/#comments</comments>
		<pubDate>Tue, 28 Sep 2010 06:04:02 +0000</pubDate>
		<dc:creator>sugimoto</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://labo.opengroove.com/blog/?p=650</guid>
		<description><![CDATA[sugimotoです。 Ruby on Rails にはいろいろ便利な機能がありますが、前から便利だけど微妙。。と思っているのが、date_select や datetime_select です。どちらも ActionView::Helpers::DateHelper のmethod で日付入力を簡単に作れますが、年月日のプルダウン入力はちょっと。。。という感じです。 ただ、この入力、Modelのdate,datetime なカラムにそのまま突っ込んで保存してしまえるのがとっても便利です。Post.published_at というカラムに params = { :post => { :published_at(1i) => "2010", :published_at(2i) => "09", :published_at(3i) => "28", :published_at(4i) => "15", :published_at(5i) => "20" } } みたいな感じでcontrollerにパラメータが渡されますが、 post = Post.new(params[:post]) とするだけで、post.published_at = &#8217;2010-09-28 15:20&#8242; なレコードができてしまいます。 前置きが長くなりましたが、この仕組を調べてみました。 なお、今回例示したソースは公開時のtrunk を参照しています。 仕組みを調べてみる まずはレコードを作成する場所、つまり、 ActiveRecord::Base::initialize を見てみます。 def initialize(attributes [...]]]></description>
			<content:encoded><![CDATA[<p>
sugimotoです。
</p>

<p>
Ruby on Rails にはいろいろ便利な機能がありますが、前から便利だけど微妙。。と思っているのが、date_select や datetime_select です。どちらも ActionView::Helpers::DateHelper のmethod で日付入力を簡単に作れますが、年月日のプルダウン入力はちょっと。。。という感じです。
</p>

<p>
ただ、この入力、Modelのdate,datetime なカラムにそのまま突っ込んで保存してしまえるのがとっても便利です。Post.published_at というカラムに
</p>

<pre>
params = {
    :post => {
        :published_at(1i) => "2010",
        :published_at(2i) => "09",
        :published_at(3i) => "28",
        :published_at(4i) => "15",
        :published_at(5i) => "20"
     }
}
</pre>

<p>
みたいな感じでcontrollerにパラメータが渡されますが、
</p>

<pre>
post = Post.new(params[:post])
</pre>

<p>
とするだけで、post.published_at = &#8217;2010-09-28 15:20&#8242; なレコードができてしまいます。
</p>

<p>
前置きが長くなりましたが、この仕組を調べてみました。
なお、今回例示したソースは<a href="http://github.com/rails/rails/blob/master/activerecord/lib/active_record/base.rb">公開時のtrunk</a> を参照しています。
</p>

<h3>仕組みを調べてみる</h3>

<p>
まずはレコードを作成する場所、つまり、 ActiveRecord::Base::initialize を見てみます。
</p>

<pre class="">
       def initialize(attributes = nil)
        @attributes = attributes_from_column_definition
        @attributes_cache = {}
        @new_record = true
        @readonly = false
        @destroyed = false
        @marked_for_destruction = false
        @previously_changed = {}
        @changed_attributes = {}

        ensure_proper_type

        if scope = self.class.send(:current_scoped_methods)
          create_with = scope.scope_for_create
          create_with.each { |att,value| self.send("#{att}=", value) } if create_with
        end
        self.attributes = attributes unless attributes.nil?

        result = yield self if block_given?
        _run_initialize_callbacks
        result
      end
</pre>

<p>
どうやら、受渡されたattributes を self.attributes=(attributes) でいれているだけですね。
では self.attributes=(v) では何をしているんでしょうか。
</p>

<pre>
      def attributes=(new_attributes, guard_protected_attributes = true)
        return unless new_attributes.is_a?(Hash)
        attributes = new_attributes.stringify_keys

        multi_parameter_attributes = []
        attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes

        attributes.each do |k, v|
          if k.include?("(")
            multi_parameter_attributes < < [ k, v ]
          else
            respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(UnknownAttributeError, "unknown attribute: #{k}")
          end
        end

        assign_multiparameter_attributes(multi_parameter_attributes)
      end
</pre>

<p>
"(" が付いた attribute を複数パラメータの属性として次のような配列を作成し、 assign_multiparameter_attributes に渡しています。
</p>

</pre><pre>
[
    ["published_at(1i)", "2010"],
    ["published_at(2i)", "09"],
    ["published_at(3i)", "28"],
    ["updated_at(1i)", "2010"],
    ["updated_at(2i)", "09"],
    ["updated_at(3i)", "28"],
    ["updated_at(4i)", "15"],
    ["updated_at(5i)", "10"],
    ["published_at(4i)", "15"],
    ["published_at(5i)", "10"],
]
</pre>

<p>
では、次にassign_multiparameter_attributes を見てみます。
</p>

<pre>
      def assign_multiparameter_attributes(pairs)
        execute_callstack_for_multiparameter_attributes(
          extract_callstack_for_multiparameter_attributes(pairs)
        )
      end
</pre>

<p>
method名から察するに、一度パラメータを展開して、それを処理しているようです。展開のmethodはどんな処理でしょう。
</p>

<pre>
      def extract_callstack_for_multiparameter_attributes(pairs)
        attributes = { }

        for pair in pairs
          multiparameter_name, value = pair
          attribute_name = multiparameter_name.split("(").first
          attributes[attribute_name] = [] unless attributes.include?(attribute_name)

          parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value)
          attributes[attribute_name] < < [ find_parameter_position(multiparameter_name), parameter_value ]
        end

        attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } }
      end
</pre>

<p>
published_at(2i) のような名前から attributes["published_at"] という配列を作成して、(1i), (2i), (3i) などの値とセットで配列に積んでいっています。
さらに、名前でhashになった attributes を名前ごとにソートしています。
次のような hash が出来上がります。
</p>

<p>ソート前 - 1つ目の要素が文字列のまま渡されているので、xxxx(11i) みたいなのがあると並び替えを間違える気がしますが、どうなんでしょうね。。。
</p>

</pre><pre>
attributes = {
    "publised_at" => [["1", 2007], ["3", 28], ["4", 15], ["5", 10], ["2", 9], ],
    "updated_at" => [["1", 2007], ["3", 28], ["4", 15], ["5", 10], ["2", 9], ],
}
</pre>

<p>ソート後 (1つ目の要素でソートされ、2つ目の要素で collect された)
</p>

<pre>
attributes = {
    "publised_at" => [2007, 9, 28, 15, 10 ],
    "updated_at" => [2007, 9, 28, 15, 10 ],
}
</pre>

<p>
type_cast_attribute_value, find_parameter_position の2つのメソッドは名前から何をしているかなんとなく想像がつきますが、一応見てみます。
</p>

<pre>
      def type_cast_attribute_value(multiparameter_name, value)
        multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value
      end
</pre>

<p>
xxxx(1i) のような名前のパラメータを to_i でtype cast した値を返します。どうやら、xxxx(1f) のような名前にすると Float にcastするようです。
</p>

<pre>
      def find_parameter_position(multiparameter_name)
        multiparameter_name.scan(/\(([0-9]*).*\)/).first.first
      end
</pre>

<p>
xxxx(1i) のようなパラメータ名から数字を取り出し、パラメータの順序を返しています。
</p>

<p>
そろそろ先が見えてきた感じがします。(1i) に従って配列にされたパラメータの処理をする execute_callstack_for_multiparameter_attributes を見てみます。
</p>

<pre>
      def execute_callstack_for_multiparameter_attributes(callstack)
        errors = []
        callstack.each do |name, values_with_empty_parameters|
          begin
            klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass
            # in order to allow a date to be set without a year, we must keep the empty values.
            # Otherwise, we wouldn't be able to distinguish it from a date with an empty day.
            values = values_with_empty_parameters.reject { |v| v.nil? }

            if values.empty?
              send(name + "=", nil)
            else

              value = if Time == klass
                instantiate_time_object(name, values)
              elsif Date == klass
                begin
                  values = values_with_empty_parameters.collect do |v| v.nil? ? 1 : v end
                  Date.new(*values)
                rescue ArgumentError => ex # if Date.new raises an exception on an invalid date
                  instantiate_time_object(name, values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
                end
              else
                klass.new(*values)
              end

              send(name + "=", value)
            end
          rescue => ex
            errors < < AttributeAssignmentError.new("error on assignment #{values.inspect} to #{name}", ex, name)
          end
        end
        unless errors.empty?
          raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes"
        end
      end
</pre>

<p>
なかなか長いです。。前半の klass = (....).klass でカラムの型を取ってきて、Time であれば、attributes の配列を instantiate_time_object で Date であれば、Date.new でインスタンス化して、最後に send(name + "=", value) でインスタンス化した値をカラムにセットしています。
Date でも Timeでもなかった場合は、klass.new(*values) で強引にインスタンス化しようとしますね。強気です。
</p>

<h3>最後に</h3>

<p>
なぜ、datetime_select を調べたかというと、datetime なカラムの入力フォームを作成するときに日付と時間を別にして日付部分をdatepicker にできないかな、と考えていたからでした。
</p>

<p>
xxxxx(1i) 的なパラメータ名を設定して、上記処理を通ったあとに、Date.new できる配列になれば良いってことで、やっぱり、datetime_select が生成するようなhashを作らないといけないんだな。。って感じです。
</p>
</pre>]]></content:encoded>
			<wfw:commentRss>http://labo.opengroove.com/blog/2010/09/28/rails%e3%81%aedatetime_select%e3%81%ae%e4%bf%9d%e5%ad%98%e3%81%ae%e4%bb%95%e7%b5%84%e3%81%bf%e3%82%92%e8%aa%bf%e3%81%b9%e3%81%a6%e3%81%bf%e3%82%8b/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ActiveRecord の conditions を作成するためのクラスを作ってみた</title>
		<link>http://labo.opengroove.com/blog/2010/06/28/activerecord-%e3%81%ae-conditions-%e3%82%92%e4%bd%9c%e6%88%90%e3%81%99%e3%82%8b%e3%81%9f%e3%82%81%e3%81%ae%e3%82%af%e3%83%a9%e3%82%b9%e3%82%92%e4%bd%9c%e3%81%a3%e3%81%a6%e3%81%bf%e3%81%9f/</link>
		<comments>http://labo.opengroove.com/blog/2010/06/28/activerecord-%e3%81%ae-conditions-%e3%82%92%e4%bd%9c%e6%88%90%e3%81%99%e3%82%8b%e3%81%9f%e3%82%81%e3%81%ae%e3%82%af%e3%83%a9%e3%82%b9%e3%82%92%e4%bd%9c%e3%81%a3%e3%81%a6%e3%81%bf%e3%81%9f/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 03:41:22 +0000</pubDate>
		<dc:creator>morimoto</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://labo.opengroove.com/blog/?p=611</guid>
		<description><![CDATA[どうもお久しぶりです。 morimotoです。 今日は複雑なActiveRecordの条件句を作成する際に（もしかしたら）楽になるのではないかと思いconditionを生成するクラスを作ってみました。 class ARCond module OPERATION EQUAL = '=' NOT_EQUAL = '' IN = 'IN' GREATER = '>' GREATER_OR_EQUAL = '>=' LESS = '< ' LESS_OR_EQUAL = ']]></description>
			<content:encoded><![CDATA[<p>どうもお久しぶりです。</p>

<p>morimotoです。</p>

<p>今日は複雑なActiveRecordの条件句を作成する際に（もしかしたら）楽になるのではないかと思いconditionを生成するクラスを作ってみました。</p>

<pre>
  class ARCond
    module OPERATION
      EQUAL            = '='
      NOT_EQUAL        = '<>'
      IN               = 'IN'
      GREATER          = '>'
      GREATER_OR_EQUAL = '>='
      LESS             = '< '
      LESS_OR_EQUAL    = '<='
    end

    attr_reader :conditions, :parameters, :separator, :table_name

    def initialize(separator="AND", table_name=nil)
      @conditions = []
      @parameters = []
      @separator  = separator
      @table_name = table_name
    end

    # column = ?
    def equal(column, value, table=nil)
      add(column, value, OPERATION::EQUAL, table)
    end
    # column <> ?
    def not_equal(column, value, table=nil)
      add(column, value, OPERATION::NOT_EQUAL, table)
    end
    # column IN (?,?,?...)
    def in(column, value, table=nil)
      add(column, value, OPERATION::IN, table)
    end
    # column > ?
    def greater(column, value, table=nil)
      add(column, value, OPERATION::GREATER, table)
    end
    # column >= ?
    def greater_or_equal(column, value, table=nil)
      add(column, value, OPERATION::GREATER_OR_EQUAL, table)
    end
    # column < ?
    def less(column, value, table=nil)
      add(column, value, OPERATION::LESS, table)
    end
    # column <= ?
    def less_or_equal(column, value, table=nil)
      add(column, value, OPERATION::LESS_OR_EQUAL, table)
    end

    def << (other)
      cond = nil
      param = []
      if other.kind_of? ARCond
        c = other.build
        cond = c.delete_at(0)
        param = c
      elsif other.kind_of? String
        cond = other
      elsif other.kind_of? Array
        cond = other.delete_at(0)
        param = other
      end
      unless cond.blank?
        @conditions << cond
        @parameters.concat(param)
      end
      return self.build
    end

    # [conditions, param, param, param,...]
    def build
      [join_conditions].concat(@parameters)
    end

    private
    def join_conditions
      sep = " #{@separator} "
      "(#{@conditions.join(sep)})"
    end

    def column_fullname(column, table=nil)
      unless column =~ /^[\w]+\.[\w]+$/
        if table_name = table.blank? ? @table_name : table
          return "#{table_name}.#{column}"
        end
      end
      column
    end

    def add(column, value, operation, table=nil)
      parts = [column_fullname(column, table), operation]
      param = [value].flatten
      parts << ((operation == OPERATION::IN) ? "(#{param.map{'?'}.join(',')})" : "?")
      self << [parts.join(' ')].concat(param)
    end
  end
</pre>

<p>使い方の例）</p>

</pre><pre>
# 基本スタイル
c1 = ARCond.new("AND")
c1.equal("col1", true)
  # => ["(col1 = ?)", true]
c1.not_equal("col2", nil)
  # => ["(col1 = ? AND col2 <> ?)", true, nil]
c1.in("col3", [31,32,33])
  # => ["(col1 = ? AND col2 <> ? AND col3 IN (?,?,?))", true, nil, 31, 32, 33]



# 連結文字を変更する
c2 = ARCond.new("OR")

# 指定した連結文字で結合されていく
c2.greater("col4", 100)
  # => ["(col4 > ?)", 100]
c2.less("col4", 200)
  # => ["(col4 > ? OR col4 < ?)", 100, 200]

# 配列みたいに追加していく
c1 << c2
  # => ["(col1 = ? AND col2 <> ? AND col3 IN (?,?,?) AND (col4 > ? OR col4 < ?))", true, nil, 31, 32, 33, 100, 200]



# 引数なしはANDで連結
c3 = ARCond.new()

# いつもどおりの配列の conditions もくっつけれる
c3 << ["col5 = ? AND col6 IN (?,?)", 11,22,33]
  # => ["(col5 = ? AND col6 IN (?,?))", 11, 22, 33]

# 任意文字列もくっつけれる
c3 < < "col7 > col8"
  # => ["(col5 = ? AND col6 IN (?,?) AND col7 > col8)", 11, 22, 33]


# テーブル名を指定する
c4 = ARCond.new("OR", "sample")

# カラム名の頭にテーブル名が付与される
c4.greater_or_equal("col9", 300)
  # => ["(sample.col9 >= ?)", 300]
c4.less_or_equal("col9", 400)
  # => ["(sample.col9 >= ? OR sample.col9 < = ?)", 300, 400]

# くっつけるときにテーブル名を指定する
c4.equal("col10", false, "banana")
  # => ["(sample.col9 >= ? OR sample.col9 < = ? OR banana.col10 = ?)", 300, 400, false]

c3 << c4
  # => ["(col5 = ? AND col6 IN (?,?) AND col7 > col8 AND (sample.col9 >= ? OR sample.col9 < = ? OR banana.col10 = ?))", 11, 22, 33, 300, 400, false]

c1 << c3
  # => ["(col1 = ? AND col2 <> ? AND col3 IN (?,?,?) AND (col4 > ? OR col4 < ?) AND (col5 = ? AND col6 IN (?,?) AND col7 > col8 AND (sample.col9 >= ? OR sample.col9 < = ? OR banana.col10 = ?)))", true, nil, 31, 32, 33, 100, 200, 11, 22, 33, 300, 400, false]


# 最終的に使いたいタイミングで build してあげたらよい
c1.build
  # => ["(col1 = ? AND col2 <> ? AND col3 IN (?,?,?) AND (col4 > ? OR col4 < ?) AND (col5 = ? AND col6 IN (?,?) AND col7 > col8 AND (sample.col9 >= ? OR sample.col9 < = ? OR banana.col10 = ?)))", true, nil, 31, 32, 33, 100, 200, 11, 22, 33, 300, 400, false]

</pre>

<p>作っておいてなんですが、テーブルが複数あったり、集計クエリが絡んできたりと、複雑になればなるほど自分でwhere句を書いたほうが早い気がします。</p>

<p>以上、morimoto でした。</p>
</pre>]]></content:encoded>
			<wfw:commentRss>http://labo.opengroove.com/blog/2010/06/28/activerecord-%e3%81%ae-conditions-%e3%82%92%e4%bd%9c%e6%88%90%e3%81%99%e3%82%8b%e3%81%9f%e3%82%81%e3%81%ae%e3%82%af%e3%83%a9%e3%82%b9%e3%82%92%e4%bd%9c%e3%81%a3%e3%81%a6%e3%81%bf%e3%81%9f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails のデータベースにMS SQL Serverのリンクサーバーを使うためのメモ</title>
		<link>http://labo.opengroove.com/blog/2009/07/06/rails-%e3%81%ae%e3%83%87%e3%83%bc%e3%82%bf%e3%83%99%e3%83%bc%e3%82%b9%e3%81%abms-sql-server%e3%81%ae%e3%83%aa%e3%83%b3%e3%82%af%e3%82%b5%e3%83%bc%e3%83%90%e3%83%bc%e3%82%92%e4%bd%bf%e3%81%86%e3%81%9f/</link>
		<comments>http://labo.opengroove.com/blog/2009/07/06/rails-%e3%81%ae%e3%83%87%e3%83%bc%e3%82%bf%e3%83%99%e3%83%bc%e3%82%b9%e3%81%abms-sql-server%e3%81%ae%e3%83%aa%e3%83%b3%e3%82%af%e3%82%b5%e3%83%bc%e3%83%90%e3%83%bc%e3%82%92%e4%bd%bf%e3%81%86%e3%81%9f/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 06:02:41 +0000</pubDate>
		<dc:creator>sugimoto</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://labo.opengroove.com/blog/?p=50</guid>
		<description><![CDATA[そんなケースはほとんどないかもしれませんが。。 先日実際にあったのでそのときのメモです。 Ruby on Rails (v2.2) による社内システムをお客様の既存システムと連携をするために、次の条件で実装しました。 データベースエンジンにMS SQL Server 2000を使う 既存システムのデータベースとの連携をリアルタイムに行う 既存システムのデータベースへの参照、更新はリアルタイムに行う必要があったため、リンクサーバーをviewで参照することにしました。 RailsアプリケーションはWindowsサーバー上に設置することにしました。 1. まずはSQLサーバーに接続 SQLサーバーをエンジンとして使うにはSQLサーバー用のアダプタが必要なので、インストールします。 Connect To MicrosoftSQLServer From Rails On Linux Boxを参考にしてインストール > gem install rails-sqlserver-2000-2005-adapter -s http://gems.github.com Ruby/DBIにふくまれるADO.rb を C:\ruby\lib\ruby\site_ruby\1.8\DBD\ADO にコピーします。 database.yml の設定はいつも通りです。 adapter をMSSQL用に変更 さらに、Rails上では文字コードはUTF-8の方が何かと安心なので、environment.rb に次のように指定します。 require 'win32ole' WIN32OLE.codepage = WIN32OLE::CP_UTF8 2. 既存システムの複合キーを解釈する 既存システムのidは当然ですが、Railsの規約通りではありませんでした。 さらに、メインのテーブルに複合キーがあり、複数カラムでユニークキーとなっていました。 とはいえ、Rails のHABTMを使いたいので、Composite Primary Keys プラグインを利用しました。 [...]]]></description>
			<content:encoded><![CDATA[<p>そんなケースはほとんどないかもしれませんが。。</p>

<p>先日実際にあったのでそのときのメモです。</p>

<p>Ruby on Rails (v2.2) による社内システムをお客様の既存システムと連携をするために、次の条件で実装しました。</p>

<ul>
    <li>データベースエンジンにMS SQL Server 2000を使う</li>
    <li>既存システムのデータベースとの連携をリアルタイムに行う</li>
</ul>

<p>既存システムのデータベースへの参照、更新はリアルタイムに行う必要があったため、リンクサーバーをviewで参照することにしました。</p>

<p>RailsアプリケーションはWindowsサーバー上に設置することにしました。</p>

<h3>1. まずはSQLサーバーに接続</h3>

<p>SQLサーバーをエンジンとして使うにはSQLサーバー用のアダプタが必要なので、インストールします。</p>

<p><a href="http://wiki.rubyonrails.org/database-support/ms-sql">Connect To MicrosoftSQLServer From Rails On Linux Box</a>を参考にしてインストール</p>

<pre>
> gem install rails-sqlserver-2000-2005-adapter -s http://gems.github.com
</pre>

<p><a href="http://rubyforge.org/projects/ruby-dbi/">Ruby/DBI</a>にふくまれるADO.rb を C:\ruby\lib\ruby\site_ruby\1.8\DBD\ADO にコピーします。</p>

<p>database.yml の設定はいつも通りです。
adapter をMSSQL用に変更</p>

<p>さらに、Rails上では文字コードはUTF-8の方が何かと安心なので、environment.rb に次のように指定します。</p>

<pre>
require 'win32ole'
WIN32OLE.codepage = WIN32OLE::CP_UTF8
</pre>

<h3>2. 既存システムの複合キーを解釈する</h3>

<p>既存システムのidは当然ですが、Railsの規約通りではありませんでした。
さらに、メインのテーブルに複合キーがあり、複数カラムでユニークキーとなっていました。</p>

<p>とはいえ、Rails のHABTMを使いたいので、<a href="http://compositekeys.rubyforge.org/">Composite Primary Keys</a> プラグインを利用しました。</p>

<pre>
> gem install composite_primary_keys
</pre>

<p>environment.rb に次の行を追加します。</p>

<pre>
require 'composite_primary_keys'
</pre>

<p>model では次のようにして複合キーを指定しました。</p>

<pre>
set_primary_keys :col1, :col2
has_one :status, :foreign_key => ['col1', 'col2']
</pre>

<h3>3. リンクサーバーに接続</h3>

<p>これで設定はOKかなと思ったんですが、実際に動かしてみると2つの問題がありました。</p>

<h4 style="font-size: 100%;">1つ目、更新できない。。</h4>

<p>致命的です。更新しようとするとエラーが発生してしまいました。
調べてみると、<a href="http://msdn.microsoft.com/ja-jp/library/ms177403.aspx">分散クエリと分散トランザクション</a>に説明がありました。</p>

<p>長い、、、ですが、問題になっているのはここ。</p>

<blockquote>
上記の規則は、入れ子になったトランザクションをサポートしないプロバイダに対する制限事項として、分散トランザクションでの更新操作は、XACT_ABORT が ON の場合のみ行えることを示しています。
</blockquote>

<p>リンクサーバーによる接続は「入れ子になったトランザクションをサポートしないプロバイダ」ということ。
RailsではRailsの機能でリクエストごとにトランザクションが発生してしまうので、リンクサーバによる接続時に自動的に発生するローカルトランザクションと入れ子になってしまうようです。</p>

<p>回避する方法として、「SET XACT_ABORT ON」にして、トランザクションが入れ子になることを許容するようにしました。</p>

<p>Railsがトランザクションを開始する前に実行するために、environment.rb に次のコードを入れて、接続直後にSQLを実行するようにしました。</p>

<pre>
# リンクサーバーに対応するために接続後に XACT_ABORT ON にする
module ActiveRecord
  module ConnectionAdapters
    class SQLServerAdapter < AbstractAdapter
      alias :initialize_original :initialize

      def initialize(connection, logger, connection_options=nil)
        initialize_original(connection, logger, connection_options)
        @connection.execute("SET XACT_ABORT ON")
      end
    end
  end
end
</pre>

<h4 style="font-size: 100%;">2つ目、リンクサーバーへの接続が大量に発生</h4>

<p>もうひとつ、アプリケーションを使っているとリンクサーバーへの接続が大量に発生してしまうということがありました。
実は、原因はわからなかったのですが、この接続がリンク先のリソースをロックする状況が発生していました。</p>

<p>対策として、productionモードでもRailsに接続を保持させないようにすることにしました。</p>

<p>environment.rb に以下を追加</p>

</pre><pre>
require 'action_controller/dispatcher'
ActionController::Dispatcher.after_dispatch do
  ActiveRecord::Base.clear_reloadable_connections!
end
</pre>

<p>さて、正直なところ、これが正解かわかりませんが。試行錯誤の末、社内システムは無事に稼動しています。</p>
]]></content:encoded>
			<wfw:commentRss>http://labo.opengroove.com/blog/2009/07/06/rails-%e3%81%ae%e3%83%87%e3%83%bc%e3%82%bf%e3%83%99%e3%83%bc%e3%82%b9%e3%81%abms-sql-server%e3%81%ae%e3%83%aa%e3%83%b3%e3%82%af%e3%82%b5%e3%83%bc%e3%83%90%e3%83%bc%e3%82%92%e4%bd%bf%e3%81%86%e3%81%9f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

