ラベル rails の投稿を表示しています。 すべての投稿を表示
ラベル rails の投稿を表示しています。 すべての投稿を表示

2012年12月11日火曜日

railsのhelper便利すぎw

counter_partyのview
<%= f.collection_select(:名前, モジュール.find_all_by_列("値"), :列val用, :列disp用) %>
<%= f.collection_select(:CPCategory1, MiscCode.find_all_by_MiCodeKey("Field"), :MiCodeName, :MiCodeName) %>
↓
<select id="counter_party_CPCategory2" name="counter_party[CPCategory2]">
  <option value="顧客">顧客</option>
  <option value="外注先">外注先</option>
  <option value="その他">その他</option>
</select>

2012年12月6日木曜日

既存データベース(SQL Server)をRailsに載せる

ごめんなさい、ちょっと長すぎて、途中で何を言っているかわからなくなった気がする...でも一応個人の作業メモということで...お許し下さい..orz

環境はwindows
Ruby on Rails(RoR)は「railsinstaller.org」からdownload

$ ruby --version
ruby 1.9.3p125 (2012-02-16) [i386-mingw32]
$ rails --version
Rails 3.2.1
$ gem --version
1.8.16
$ gem list
*** LOCAL GEMS ***
actionmailer (3.2.1)
actionpack (3.2.1)
activemodel (3.2.9, 3.2.1)
activerecord (3.2.1)
activerecord-sqlserver-adapter (3.2.10, 3.2.1)
...
...

VersionやGemの一覧(初期ではない、あとからGEMで追加したものもある!)
インストール後、デフォルト「c:\Sites」が作成される
※もしOS上既にRubyがインストールしていれば、複数バージョンを管理するために,pikをススメます
参照 http://holypp.hatenablog.com/entry/20110407/1302193459

$ gem install pik


さて、プロジェクトを建てましょう

$ rails new railsinstaller_demo
$ cd railsinstaller_demo


今回は、既存のデータベースを使って、RoRに乗り換える。DBはSQL Server
Rails3からはプロジェクト単位でGEMを管理するから、プロジェクトフォルダ直下のGemfileに追加

gem 'activerecord-sqlserver-adapter'
gem 'tiny_tds'

そしたら、実行

$ rail bundle install


次はDBに接続
config/database.ymlを編集

development:
adapter: sqlserver
database: DB_NAME
host: 192.168.1.XXX
username: user
password: pwd


migrate←この段階では必要ないかもしれr内が、まぁ私はやった

$ rake db:migrate


ここまで来て、次はscaffold。だけど既存のDBのテーブルにはid列もないし、テーブル名はRailsの複数形式に従っていないが、ここ参照しました。本当にたすかったよ!
例えば今回scaffoldしたいテーブル名は「CounterParty」

$ rails console

irbコンソールが表示されたら、下記コードを全部(テーブル名は変更してね)コピペ
name = 'CounterParty'
si_table_name = 'CounterParty'
si_field_names = Array.new
si_cols = ActiveRecord::Base.connection.columns(si_table_name,"#{name} Columns")
si_cols.each do |c|
si_field_names << "#{c.name}:#{c.type}"
end
puts si_field_names.join(' ')
putsされたのは既存「CounterPartyのテーブル構造」、それをコピして、一旦railsコンソールをexit $ rails g scaffold CounterParty コピーした内容をここにペスト Another migration is already named create_counter_parties:... あれ、作成できない、既にある?なるほど、これはさきmigrateが悪かったね、しなければ良かったかも skip-migrateオプションを追加してもう一回 $ rails g scaffold CounterParty コピーした内容をここにペスト --skip-migrate Overwriteと聞かれたら「Y」 ... .. そしてCOunterPartyのScaffoldが作成されました。 しかし、DBの構造はRailsに乗ってないので、いま表示したらエラーになりますので app\models\counter_party.rbを編集して、テーブル名とid列を指定
class CounterParty < ActiveRecord::Base
 attr_accessible :CPName, :CPMemo, ... #Rails3からはwrite可能なフィルドを明示的に宣言しないといけないらしい?
 self.table_name = 'CounterParty'
 self.primary_key = :CPCPID
end
これでOKのはず、さあ見てみよ $ rails s ブラウザーで「http://localhost:3000/counter_parties」をいれてご― 表示されたかな? 続き、WindowServer2008で動かす >ruby --version ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32] >rails --version Rails 2.1.1 >gem --version 0.9.4 だいぶ古いですね Rails3とRails2はいろいろ変わったので、ソースコードはそのまま移して使えないので、プロジェクトを新規作成する。 プロジェクト作成 database.ymlを編集 mongrelで動かすので、サービスとして登録します。 プロジェクトフォルダーの下で、「cmd」というフォルダーを作成して、下記のbatファイルを作成する mongrel_service_regist.bat CD ../ CALL mongrel_rails service::install -N "Mongrel 9500 MyProj" -p 9500 -e development -a 0.0.0.0 SC CONFIG "Mongrel 9500 MyProj" START= AUTO 9500はポート番号、他の空いているポートもOK mongrel_service_remove.bat mongrel_rails service::remove -N "Mongrel 9500 MyProj" mongrel_service_restart.bat NET STOP "Mongrel 9500 MyProj" NET START "Mongrel 9500 MyProj" mongrel_service_start.bat NET START "Mongrel 9500 MyProj" mongrel_service_stop.bat NET STOP "Mongrel 9500 MyProj" これで、サービス登録[自動に設定]、再起動、開始、停止などがOne Clickでできるようになる ※但し、これは「管理者:コマンドプロンプト」で実行しなければなりません。 SQL Serverを使っている、データベースの日本語がviewで文字化けている時。 RoRのソースコードはすべてUTF8で記載、SQLServerのencodeはsjisの場合に発生?と思う config/environment.rbの先頭で、下記を追加すれば解消された。
$KCODE = "u"
require "win32ole"
WIN32OLE.codepage=WIN32OLE::CP_UTF8
最後、既存DBを使っているので、既存のprimary key列「CPCPID」(AUTO_INCREMENT利用しない)をrailsで管理する。 sql server では「IDENTITY」という属性らしい。「開始番号」の「IDENTITYシード」と「ID増分」がある 例えばIDENTITYシード=100、ID増分=10なら、「100,110,120」みたいに自動IDを生成してくれる。 Microsoft SQL Server Management Studio(長っ!)オブジェクトエクスプローラでテーブルの「デザイン」を開き、右クリックで「列のプロパティ」でIDENTITYを設定することが可能です。 もしなんか「一旦削除しないといけない」的なメッセージで怒られたら、 「ツール」>「オプション」>「デザイナ」>「デーブルデザイナおよび...」>「テーブルの再作成を必要とする変更.....」のチェックを外せば、変更できると思います。 それが終わったら、moduleでid列として、newとeditから削除すれば、普通にidとしてrailsが管理更新してくれます。
self.primary_key = :CPCPID

長すぎで自分も嫌になりました、よしっ!以上!ヽ(´ー`)ノ フッ

2012年3月25日日曜日

amchartのamstockとRuby on Railsでファンドの基準価額を描画する、

javascriptベースのamchartではなく一つ古いのflash版でやりました。http://www.amcharts.com/

amchartに食わせるデータは基本2つ:
①チャートの設定ファイル、よくあるのはsettings.xml
②データファイル、xml,csv,jsonなど対応して、実際の描画用のデータが渡される。
※データファイルが設定ファイルの中にインクルードされる方法と、設定ファイルの中に直接データを書き出し(データファイルが無くでもいける)

今回はsetting.xmlを固定ファイルにして、データだけrailsで動的に生成するやり方で作った

setting.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Only the settings with values not equal to defaults are in this file. If you want to see the
full list of available settings, check the amstock_settings.xml file in the amstock folder. -->
<settings>
  <margins>0</margins>
  <text_size>10</text_size>

  <number_format>
    <letters>
       <letter number="1000">千</letter>
       <letter number="1000000">百万</letter>
       <letter number="1000000000">億</letter>
    </letters>
  </number_format>

  <date_formats>
    <x_axis>
      <days>MM/DD</days>
      <months>MM</months>
    </x_axis>
    <legend>
      <days>YYYY/MM/DD</days>
      <weeks>YYYY/MM/DD</weeks>
      <months>YYYY/MM/DD</months>
    </legend>
  </date_formats>
  
  <data_sets>
    
    <data_set did="0">
       <title>ファンドA</title>
       <color>FF0000</color>
       <file_name>../../fund/search/data/123</file_name>
       <main_drop_down selected="true"></main_drop_down>
       <csv>
         <reverse>true</reverse>
         <separator>,</separator>
         <date_format>YYYY-MM-DD</date_format>
         <decimal_separator>.</decimal_separator>
         <columns>
           <column>date</column>
           <column>close</column>
         </columns>
       </csv>
    </data_set>

    <data_set did="1">
       <title>ファンドB</title>
       <color>FF00BB</color>
       <short>[ぶどうの実]</short>
       <file_name>../../fund/search/data/456</file_name>
       <csv>
         <reverse>true</reverse>
         <separator>,</separator>
         <date_format>YYYY-MM-DD</date_format>
         <decimal_separator>.</decimal_separator>
         <columns>
           <column>date</column>
           <column>close</column>
         </columns>
       </csv>
    </data_set> 

    <data_set did="3">
       <title>日経平均株価(日経225)</title>
       <short>日経255</short>
       <compare_list_box selected="true"></compare_list_box>
       <color>999999</color>
       <file_name>../../fund/search/data/634</file_name>
       <csv>
         <reverse>true</reverse>
         <separator>,</separator>
         <date_format>YYYY-MM-DD</date_format>
         <decimal_separator>.</decimal_separator>
         <columns>
           <column>date</column>
           <column>close</column>
         </columns>
       </csv>
    </data_set>

  </data_sets>

  <charts>
   <chart cid="0">
    <bg_color>f5f5f5,ffffff</bg_color>
      <border_color>#CCCCCC</border_color>
      <border_alpha>100</border_alpha>
     
      <grid>
        <x>
          <dashed>true</dashed>
        </x>
        <y_right>
          <color>cccccc</color>
          <alpha>100</alpha>
          <dashed>true</dashed>
        </y_right>
      </grid>

      <legend>
        <show_date>true</show_date>
      </legend>

    <graphs>
     <graph gid="0">
       <axis>right</axis>
      <type>line</type>
      <data_sources>
        <close>close</close>
          </data_sources>
          
          <compare_source>close</compare_source>

        <legend>
            <date key="true" title="true"><![CDATA[<b>{close}</b>]]></date>
            <period key="true" title="true"><![CDATA[open:<b>{open}</b> low:<b>{low}</b> high:<b>{high}</b> close:<b>{close}</b>]]></period>
            <date_comparing key="true" title="true"><![CDATA[{close.percents}]]></date_comparing>
            <period_comparing key="true" title="true"><![CDATA[{close.percents}]]></period_comparing>
          </legend>
     </graph>
    </graphs>
   </chart>
  </charts>
  
  
  <data_set_selector>
  <position>top</position>
    <width>300</width>
    <max_comparing_count>4</max_comparing_count>
   <main_drop_down_title>選択</main_drop_down_title>
   <compare_list_box_title>比較</compare_list_box_title>
  </data_set_selector>
  
  <period_selector>
    <button>
      <bg_color_hover>b81d1b</bg_color_hover>
      <bg_color_selected>b81d1b</bg_color_selected>
      <text_color_hover>ffffff</text_color_hover>
      <text_color_selected>ffffff</text_color_selected>
    </button>
  
  <periods>  
     <period type="MM" count="1">1ヶ月</period>
     <period type="MM" count="3">3ヶ月</period>
     <period type="MM" count="6">6ヶ月</period>
     <period selected="true" type="YYYY" count="1">1年</period>
     <period type="YYYY" count="3">3年</period>
     <period type="YYYY" count="5">5年</period>
     <period type="YYYY" count="7">7年</period>
     <period type="MAX">設定来</period>
  </periods>
  
  <periods_title>期間:</periods_title>
  <custom_period_title>任意期間:</custom_period_title>
  </period_selector>

  <header>
    <enabled></enabled>
    <text><![CDATA[<b>{title}</b> {short} {description}]]></text>
    <text_size>12</text_size>
  </header>

  <plot_area>
    <border_color>cccccc</border_color>
  </plot_area>

  <scroller>
    <enabled>true</enabled>
    <height>50</height>
    <graph_data_source>close</graph_data_source>
    <bg_color>f5f5f5,ffffff</bg_color>
    <resize_button_color>b81d1b</resize_button_color>
  </scroller>

</settings>

controllers/fund/search_controller.rbに追加
3年以内の分配金再投資基準価額を純資産降順でcsv作成、csvは行は「yyyy-mm-dd,修正基準価額」になっている
.....
.....
  def data
    @fundCorrectionIndex = FundCorrectionIndex.find(:all, :conditions => ["fund_id=? and as_of_date >= (NOW() - INTERVAL 3 YEAR)",  params[:id]], :order => 'as_of_date desc')
    csv_data = ""
    @fundCorrectionIndex.each do |rec|
      csv_data += "#{rec.as_of_date.strftime("%Y-%m-%d")},#{rec.correction_value}\r\n"
    end
    render :text => csv_data
  end
.....
.....

htmlは
<!-- headに -->
<script type="text/javascript" src="/rsrc/amcharts/swfobject.js"></script>
<script type="text/javascript" src="/rsrc/amcharts/stockchart.js"></script>

<!-- bodyに -->
<body onLoad="draw_stock('stock','/market/special/asia/settings.xml')">

<!-- 描画用divを追加 -->
<div id="stock"></div>

stockchart.js
function draw_stock(id,setting_url,width,height) {
 if(width == undefined){
  width = "700"; 
  } 
 if(height == undefined){
  height = "500"; 
  } 
 if(setting_url == undefined){
  setting_url = "settings.xml"
  }

 var params = {
   bgcolor:"#FFFFFF"
  };
 var flashVars = {
   path: "/rsrc/amcharts/",
   settings_file: setting_url,
   data_file: "data.xml",
   chart_id: id
  };
 swfobject.embedSWF("/rsrc/amcharts/amstock.swf", id, width, height, "8.0.0", "/rsrc/amcharts/expressInstall.swf", flashVars, params);
}

2012年3月21日水曜日

RailsのActiveRecordのfindメソッドの基礎的書き方の一例

FundIndex.find(:all,
                    :select =>["fund_id,value,as_of_date"],
                    :conditions => ["fund_id=? and fund_index_type_id=?", 564,2],
                    :limit => 100)

2012年3月1日木曜日

railsコンソールでモデルのfindメソッドで関節的に関係を持つデーブルへのアクセス

3つのテーブルそれそれ下記の関係

tmp_fund_index ○----● fund ●----○ fund_ranking

#models/fund.rb
class Fund < ActiveRecord::Base
  has_many :fund_rankings
end

#models/fund_ranking.rb
class FundRanking < ActiveRecord::Base
  belongs_to :fund
end

#models/tmp_fund_index.rb
class TmpFundIndex < ActiveRecord::Base
  belongs_to :fund
end
まずコンソールで確認すると、出ました $ ruby script/console Loading development environment.
>> FundRanking.find(:all, :limit => 1, :include => [:fund => [:tmp_fund_index]])
コントローラでは
#controllers/fund/ranking_controller.rb
  @rank_dtl = FundRanking.find :all,
                               :include => [{:fund => :tmp_fund_index}],

ビューアーでは、こうやって参照できる
#views/fund/ranking/detail.rhtml
<%- if @rank_dtl -%>
  <%- @rank_dtl.each_with_index do |rank, idx| -%>
    <%= rank.fund.tmp_fund_index.standard_price %>
  <%- end -%>
<%- end -%>

2011年12月30日金曜日

前回(サーバからcsvを複数取得する)の続きに、取得したcsvをDBにinsertする

app/libの下にprice_importer.rbを作成し、app/で実行する

$ ruby script/runner PriceImporter.execute

以下の内容
require 'csv'
class PriceImporter
  class << self
    def execute()
      begin
          result = system("/path/to/script/getfile.sh")  #←<a href="http://kagen88.blogspot.com/2011/12/shelllftp.html">前回作成したshellスクリプト</a>
          print result
          Dir::glob("/path/to/data/*.csv").each {|f|  #←取得したcsvファイルを保存する場所の(すべての?)csvをループ
            puts "#{f}: #{File::stat(f).size} bytes"  #←サイズを表示してみる
            cf=File.open(f,"r")  #←開く
            buf=cf.read()  #←読む
            @parsed_file = CSV::Reader.parse(convertSjis2UTF8(buf))  #←CSVハッシュに格納、その前にsjisをutf8に
            @parsed_file.shift  #←最初のタイトル行をスキップ
            @parsed_file.each  do |row|
              pd = Product.find_by_code(row[0])  #←既存のテーブルモデルを使って、コードの有無を確認
              if pd
                Price.delete_all "pd_id = " + pd.id.to_s + " AND base_date_on = '" + row[4] + "'"  #←上書きしたいので、一致したレコードを削除
                p = Price.new
                p.pd_id = pd.id
                p.base_date_on = row[4]
                p.price = row[5]
                p.save  #←インサート
              else
                RAILS_DEFAULT_LOGGER.debug("コード(" + row[0] + ")がproductsテーブルに存在しない。ご確認ください。")
                puts "コード(" + row[0] + ")がproductsテーブルに存在しない。ご確認ください。"
              end
            end
          }
      rescue => e
        RAILS_DEFAULT_LOGGER.debug(e)
        raise
      end
    end
    def convertSjis2UTF8(val)←utf8変換
      val.kconv(Kconv::UTF8, Kconv::SJIS) unless val.blank?
    end
  end
end
以上

2011年12月20日火曜日

CentOS6(64bit)にHTML+CSSをPDFに変換するprince8

railsのプロジェクトでHTML+CSSをPDFに変換する必要がありました。
ApacheのFOPがありました。無料ですが、それはHTMLとCSSではなくXSL-FO(XML)からPDFに変更するというものでした。しかもいろいろできないことが有るみたい(文字を画像の回り込みなど)。
さらに調べたら、princeがあって、HTML+CSSをPDFに変換できる。特徴はいろいろ、かなりイケてる感じ
1.各プラットフォームに対応http://www.princexml.com/download/
2.PDFファイルの出力は当然ですが、標準出力も対応
3.テーブルの中でページが割れないように設定できる
4.ヘッダー、フッター、ページナーンバー
5.大きくしてもボヤけないSVGの読み込みが対応
6.いろんな言語のWrappersがある(Java/Python/Perl/PHP/VB....)⇒rubyがない…でも大丈夫みたい
取り敢えずインストールしてみる

$ cat /etc/redhat-release
CentOS Linux release 6.0 (Final)
$ uname -a
Linux localhost.localdomain 2.6.32-71.el6.x86_64 #1 SMP Fri May 20 03:51:51 BST 2011 x86_64 x86_64 x86_64 GNU/Linux

OSはCentOS6(64bit)みたい。
ここからダウンロード
RHEL5: CentOS 5.5 / 64-bit
prince-8.0-1.centos55.x86_64.rpm

$ cd ~/download
$ wget http://www.princexml.com/download/prince-8.0-1.centos55.x86_64.rpm

普通にインストールしたら怒られた、openssl64bitはちゃんとあるのに

$ sudo rpm -ivh prince-8.0-1.centos55.x86_64.rpm
エラー: 依存性の欠如:
libcrypto.so.6()(64bit) は prince-8.0-1.x86_64 に必要とされています
libcurl.so.3()(64bit) は prince-8.0-1.x86_64 に必要とされています
libexpat.so.0()(64bit) は prince-8.0-1.x86_64 に必要とされています
libfontconfig.so.1()(64bit) は prince-8.0-1.x86_64 に必要とされています
libfreetype.so.6()(64bit) は prince-8.0-1.x86_64 に必要とされています
libgif.so.4()(64bit) は prince-8.0-1.x86_64 に必要とされています
libjpeg.so.62()(64bit) は prince-8.0-1.x86_64 に必要とされています
libpng12.so.0()(64bit) は prince-8.0-1.x86_64 に必要とされています
libpng12.so.0(PNG12_0)(64bit) は prince-8.0-1.x86_64 に必要とされていま す
libssl.so.6()(64bit) は prince-8.0-1.x86_64 に必要とされています
libtiff.so.3()(64bit) は prince-8.0-1.x86_64 に必要とされています
libungif.so.4()(64bit) は prince-8.0-1.x86_64 に必要とされています
[kagen@localhost download]$ rpm -qa | grep openssl-devel
openssl-devel-1.0.0-4.el6_0.2.x86_64

検索したら、ここにたどり着いた。同じ困っている人がいた。http://www.princexml.com/bb/viewtopic.php?f=2&t=7021
8.1から対応してくれそうです。

$ wget http://www.princexml.com/download/prince-8.0-linux-amd64-static.tar.gz
....
$ tar xzvf prince-8.0-linux-amd64-static.tar.gz
....
$ cd prince-8.0-linux-amd64-static
$ sudo ./install.sh
[sudo] password:
Prince 8.0

Install directory
This is the directory in which Prince 8.0 will be installed.
Press Enter to accept the default directory or enter an alternative.
[/usr/local]:⇒ブランクのままエンター

Installing Prince 8.0...
Creating directories...
Installing files...

Installation complete.
Thank you for choosing Prince 8.0, we hope you find it useful.
Please visit http://www.princexml.com for updates and development news.
$ prince --version
Prince 8.0
Copyright 2002-2011 YesLogic Pty. Ltd.
Non-commercial License

取り敢えずインストール出来たみたい。

2011年11月18日金曜日

railsでdb migrateしたら怒られたのでgemをダウングレード

railsでdb migrateしたら怒られた

WARNING: 'require 'rake/rdoctask'' is deprecated. Please use 'require 'rdoc/task' (in RDoc 2.4.2+)' instead.

gemのバージョンが高すぎるからgem 1.3.7にダウングレードする

# gem -v
1.8.7
# gem update --system 1.3.7
# gem -v
1.3.7

あとgemのmysqlも入れてないからいれる

# gem install mysql

これでdb:migrateしたらうまくいった

# rake db:migrate

ちなみに、すべてのテーブルを削除する方法は

# rake db:migrate VERSION=0

2011年11月10日木曜日

railsのscaffoldで作成したcontrollerが余計のお世話をする

railsのscaffoldを作成したら、controllerでactionを追加したら、actionをidとして探してしまうという余計のお世話は、実はscaffoldの仕業
rorr(ruby on rails rookie)の私にyuoさんがいろいろ教えてくれてありがとうございました。

$ rails anydesign -d mysql #まずはプロジェクト作成(データベースはmysql)
$ cd anydesign
$ rake db:create #DB作成
$ ruby script/generate scaffold report title:string header:text body:text footer:text #scaffoldで簡単なreport機能を作成
$ rake db:migrate #DBを更新
$ ruby script/server #サーバを立ててみる

ブラウザーでhttp://localhost:3000/を叩いたら、タイムアウト…
調べたら、iptables(firewall)がオンになってる

$ sudo service iptables status #状態を調査する
$ sudo service iptables stop #やっぱりオンになってるから、止める

もう一回ブラウザーでhttp://localhost:3000/を叩いたら、出ました。on rail...
先作ったscaffoldで作ったreportを見てみるhttp://localhost:3000/report
あ!ちゃんと空の一覧が出来ました、便利。
一覧、新規、変更、削除一応全部できる。取り敢えず
title, header, body, footerを入れて、一レコードを作りました。
そして、controllerで新しいaction、「test」を追加しました、空のaction
in reports_controller.rb

def test
end

http://localhost:3000/report/testを叩いたら、[ActiveRecord::RecordNotFound (Couldn't find Report with ID=test):]という
エラーが出来ました、なぜaction名がidに無理やりも当てるの?railsの大きなお世話だね、yuoさんが教えてくれた
scaffoldで作成するとき、config/routes.rbで

map.resources :reports

を追加してくれたので、こうなった、一番簡単なのはこの一文を削除すればいいですが、config/routes.rbで

map.resources :reports, :only => ['create','show'] #適応actionを絞る
あるいは
map.resources :reports, :except=> ['test'] #action testを除外する

でもいいらしい。