Category: ‘Rails’

database.yml 等の Git管理

2014年11月18日 Posted by PURGE

Railsプロジェクトを作成し、Git等のバージョン管理システムを使用してプロジェクトをそのまま git add、git commitしてしまい公開してしまうことがある。しかし、セキュリティ上思わしくない設定ファイル等がある。

database.ymlやsecrets.yml等だ。

そこで一度バージョン管理に入れてしまった場合に、バージョン管理から外す方法。

$ git rm --cached database.yml

–cachedオプションを使用しないと、ファイル自体削除されてしまうので注意。

そして再びバージョン管理されないように.gitignoreに下記を必ず追記する。

/config/database.yml

プロジェクトをチームで共有する場合には、database.ymlをコピーしてdatabase.yml.sample等を作成し、これをバージョン管理しておく方法がよい。当然、その中身に重要情報を記述してしまっては意味が無いので注意。

ちなみに、万が一–cachedオプションを使用しないで、ファイル自体を削除して焦ってしまった時のリカバリ方法。

$ git reset HEAD database.yml
$ git checkout database.yml

これは参考までに覚え書き。

gem install mysql2 インストールエラー

2013年8月28日 Posted by PURGE

バージョンアップのたびに、何度もハマる。
今回は、WindowsXP + ruby2.0 + mysql5.5

おなじみ下記のエラー。

checking for main() in -llibmysql... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/usr/local/ruby200/bin/ruby
        --with-mysql-dir
        --without-mysql-dir
        --with-mysql-include=${mysql-dir}/include
        --with-mysql-lib=${mysql-dir}/
        --with-mysql-dir
        --without-mysql-dir
        --with-mysql-include=${mysql-dir}/include
        --with-mysql-lib=${mysql-dir}/lib
        --with-libmysqllib
        --without-libmysqllib
C:\>gem install mysql2 -- '--with-mysql-include="C:\Program Files\MySQL\MySQL Server 5.5\include" --with-mysql-lib="C:\Program Files\MySQL\MySQL Server 5.5\lib"'
Temporarily enhancing PATH to include DevKit...
Building native extensions with: '--with-mysql-include="C:\Program Files\MySQL\MySQL Server 5.5\incl
ude" --with-mysql-lib="C:\Program Files\MySQL\MySQL Server 5.5\lib"'
This could take a while...
Successfully installed mysql2-0.3.13
Parsing documentation for mysql2-0.3.13
unable to convert "\x90" from ASCII-8BIT to UTF-8 for lib/mysql2/mysql2.so, skipping
Installing ri documentation for mysql2-0.3.13
1 gem installed

毎回、gem install の引数の渡し方が良くない。シングルクウォートで囲う。

Heroku エラー

2013年8月11日 Posted by PURGE

ローカルの開発環境では動作しているアプリが、herokuにデプロイすると動作せずに下記エラー。

$heroku logs -t

at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=xxxx.herokuapp.com fwd="111.111.111.111" dyno= connect= service= status=503 bytes=

一度、アプリ自体を削除したが、同様のエラー。

結局、ローカルの環境から作成しなおした。
かなり面倒臭かった。原因不明。

rails rake db:migrate でカラム名変更

2013年8月7日 Posted by PURGE

まずは、マイグレーションファイルの自動生成。

rails generate migration RenameColumnToTargetTable

すると、下記のマイグレーションファイルが生成される。
ちなみにファイル名は環境によって異なる。

2013080112000000_rename_column_to_target_table.rb

class RenameColumnToTargetTable < ActiveRecord::Migration
  def change
    rename_column :target_table, : old_column, :new_column
  end
end

マイグレートの実行。

rake db:migrate

rake db:migrateを使用しての、運用中のDBへの更新は初めてで怖かったのであるが、難なく成功。

当然、migrate実行する前に、必ずバックアップ取っておいてね。

Herokuで使用しているClearDBへの接続

2013年6月1日 Posted by PURGE

個人的には MySQLが好きなのであるが、Herokuでは、デフォルトのDBが、Heroku Postgres になっている。
そこで、Heroku Add-onである ClearDBというMySQLアドオンを設定して利用してみる。

まずは、Herokuサイトにてログインして、ClearDBをアドオンしてみる。Igniteであれば 5MB無料で利用できる。

そして、Heroku Toolbeltコマンドラインからログインし、アドオンされた ClearDB の設定情報を確認してみる。

$ heroku config | grep CLEARDB_DATABASE_URL
CLEARDB_DATABASE_URL: mysql://userid:password@hostname.cleardb.com/heroku_12345?reconnect=true

上記の値を、DATABASE_URL (デフォルトではPostgresが設定されている)で上書き設定する。
注意点としては、使用するMySQLによって、 mysql2:// に変更すること。

$ heroku config:add DATABASE_URL='mysql2://userid:password@hostname.cleardb.com/heroku_12345?reconnect=true

問題なく設定できていれば、git pushしたアプリのmigrationが成功するはずである。

$ heroku run rake db:migrate

尚、上記の設定情報からもわかるように、MySQLツールにて設定すれば直接DBが参照可能となる。

Rails server でエラー

2013年3月21日 Posted by PURGE

新しい環境を作るのは中々一筋縄ではいかないもので。
mysqlのlibが見つからないとのことで、rails server が起動しない。

$ rails server
/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundle: dlopen(/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmysqlclient.18.dylib (LoadError)
  Referenced from: /Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundle
  Reason: image not found - /Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundle

そこで、下記のシンボリックリンクを作成した。
ちなみに、環境はMacなので、/usr/local/mysql/lib/libmysqlclient.18.dylib にライブラリ関係がインストールされているようだ。

$ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
$ rails server
=> Booting WEBrick
=> Rails 3.2.12 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2013-03-21 09:55:44] INFO  WEBrick 1.3.1
[2013-03-21 09:55:44] INFO  ruby 1.8.7 (2012-02-08) [universal-darwin12.0]
[2013-03-21 09:55:44] INFO  WEBrick::HTTPServer#start: pid=2178 port=3000

成功。

Railsセキュリティアップデート

2013年1月16日 Posted by PURGE

2013年1月8日にRailsのセキュリティアップデートがリリースされた。
使用しているRailsのバージョンは、3.2.6だったので、アプリのGemfileを下記のように書き換えてみた。

gem 'rails', '3.2.11'
#gem 'rails', '3.2.6'

アプリケーションのトップディレクトリでアップデートしてみた。

$ bundle update
Fetching gem metadata from https://rubygems.org/...........
Fetching gem metadata from https://rubygems.org/..
Installing rake (10.0.3)
Using i18n (0.6.1)
Installing multi_json (1.5.0)
Installing activesupport (3.2.11)
Using builder (3.0.4)
Installing activemodel (3.2.11)
Using erubis (2.7.0)
Using journey (1.0.4)
Installing rack (1.4.4)
Using rack-cache (1.2)
Using rack-test (0.6.2)
Using hike (1.2.1)
Using tilt (1.3.3)
Installing sprockets (2.2.2)
Installing actionpack (3.2.11)
Using mime-types (1.19)
Using polyglot (0.3.3)
Installing treetop (1.4.12)
Using mail (2.4.4)
Installing actionmailer (3.2.11)
Using arel (3.0.2)
Installing tzinfo (0.3.35)
Installing activerecord (3.2.11)
Installing activeresource (3.2.11)
Using bundler (1.1.3)
Using coffee-script-source (1.4.0)
Using execjs (1.4.0)
Using coffee-script (2.2.0)
Using rack-ssl (1.3.2)
Installing json (1.7.6) with native extensions
Using rdoc (3.12)
Using thor (0.16.0)
Installing railties (3.2.11)
Using coffee-rails (3.2.2)
Installing jquery-rails (2.2.0)
Using mysql2 (0.3.10)
Installing rails (3.2.11)
Installing sass (3.2.5)
Installing sass-rails (3.2.6)
Using uglifier (1.3.0)
Your bundle is updated! Use `bundle show [gemname]` to see where a bundled gem is installed.

あとは動作確認です。

バージョンの互換性で動作しなくなるのには気を付けて。

Rails3でjQueryMobileのsubmitが効かない。

2012年12月1日 Posted by PURGE

jQueryMobileで、submitしたのだが、なぜか上手くいかない。
formの属性に、data-ajax = “false” と指定しなければいけないらしい。
これは、どちらかと言うと jQueryMobileの仕様です。

ハマってので覚え書き。

HTML Form

<%= form_tag(item_list_path, 
	    :method => "GET", 
	    :id => "frm", 
	    "data-ajax" => false) do %>
	<fieldset data-role="controlgroup" 
		  data-type="horizontal" 
		  data-mini="true">
	<%= radio_button_tag :item, 1, true, {:class => "item"} %>
	<label for="game_id_1"> 商品1 </label>
	<%= radio_button_tag :item, 2, false, {:class => "item"} %>
	<label for="game_id_2"> 商品2 </label>
	<%= radio_button_tag :item, 3, false, {:class => "item"} %>
	<label for="game_id_0"> 商品3 </label>
	</fieldset>
<% end %>

JavaScript

<script>
	$(function() {
		$(".item").change(function(){
			$("#frm").submit();
		});
	});
</script>

gem install mysql2 でエラー

2012年11月9日 Posted by PURGE

gem install mysql2 で下記のエラー。

gem install mysql2 -v '0.3.11'
Building native extensions.  This could take a while...
ERROR:  Error installing mysql2:
        ERROR: Failed to build gem native extension.

        /usr/local/ruby193/bin/ruby extconf.rb
checking for rb_thread_blocking_region()... yes
checking for rb_wait_for_single_fd()... yes
checking for mysql.h... no
checking for mysql/mysql.h... no
-----
mysql.h is missing.  please check your installation of mysql and try again.
-----
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/usr/local/ruby193/bin/ruby
        --with-mysql-config
        --without-mysql-config


Gem files will remain installed in /usr/local/ruby193/lib/ruby/gems/1.9.1/gems/mysql2-0.3.11 for inspection.
Results logged to /usr/local/ruby193/lib/ruby/gems/1.9.1/gems/mysql2-0.3.11/ext/mysql2/gem_make.out

どうやら、mysql.h is missing とのこと。
でも、yumでインストールしたmysqlには、どうしても mysql.h が見つからない。

どうやら、下記のライブラリも必要なようであった。
mysql55-devel

 yum --enablerepo=ius,epel install mysql55-devel
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: ftp.oss.eznetsols.org
 * epel: ftp.iij.ad.jp
 * extras: ftp.oss.eznetsols.org
 * ius: archive.linux.duke.edu
 * updates: ftp.oss.eznetsols.org
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package mysql55-devel.x86_64 0:5.5.28-2.ius.el5 set to be updated
--> Finished Dependency Resolution

Dependencies Resolved

=====================================================================================================
 Package                    Arch                Version                       Repository        Size
=====================================================================================================
Installing:
 mysql55-devel              x86_64              5.5.28-2.ius.el5              ius              190 k

Transaction Summary
=====================================================================================================
Install       1 Package(s)
Upgrade       0 Package(s)

Total download size: 190 k
Is this ok [y/N]: y
Downloading Packages:
mysql55-devel-5.5.28-2.ius.el5.x86_64.rpm                                     | 190 kB     00:00
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing     : mysql55-devel                                                                 1/1

Installed:
  mysql55-devel.x86_64 0:5.5.28-2.ius.el5

Complete!

再び、gem install mysql2。

 gem install mysql2 -v '0.3.11'
Building native extensions.  This could take a while...
Successfully installed mysql2-0.3.11
1 gem installed
Installing ri documentation for mysql2-0.3.11...
Installing RDoc documentation for mysql2-0.3.11...

上手くいったようです。

Rails モデルクラスにユティリティ関数を定義する

2012年8月28日 Posted by PURGE

Userモデル内で、属性がlast_nameとfirst_nameで、別々に定義されている場合、user_name のように、関数定義をしておくと便利。
また、DBにマスタとして定義していないモデルの属性もsexのように定義すると便利。

#coding: utf-8
class User < ActiveRecord::Base
  #
  # 属性情報
  # 
  attr_accessible :first_name, :last_name, :sex_cd

  def user_name
    attributes["last_name"] + attributes["first_name"]  
  end

  def sex
    {1 => "男性", 2 => "女性"}
  end
end

下記のように呼べる。

<%= user.user_name %>
<%= user.sex[user.sex_cd] %>

基本的なところで、ハマっていたのだが、モデルクラスに、#coding: utf-8を指定しないと変なエラーにハマる。気を付けよう。