Rails:PostgreSQLエラー( ;∀;)

パソコンを再起動して、サーバーを立ち上げ直し、localhost:3000にアクセスしたらエラーが出た。

PG::ConnectionBad: could not connect to server: No such file or directory
     Is the server running locally and accepting
     connections on Unix domain socket "/tmp/.s.PGSQL.5432”?

試してみたこと

■パスが認識されていないのかも?

export PGDATA=/usr/local/var/postgres

■一旦、アンインストールする

$ brew uninstall postgresql
$ brew install postgresql

もう一度アクセスすると、エラーが変わった!前進

FATAL:  database "myapp_development" does not exist
Run `$ bin/rake db:create db:migrate` to create your database
$ ps aux|grep sql
myname        7638   0.0  0.1  2603532  13480   ??  S     6:18PM   0:00.02 /usr/local/opt/postgresql/bin/postgres -D /usr/local/var/postgres -r /usr/local/var/postgres/server.log
myname        7689   0.0  0.0  2442000    624 s012  S+    6:19PM   0:00.00 grep sql

DBを作り直す

$ rake db:create
$ rake db:migrate

再起動時にPostgreSQL自動起動してないからよくなかったのでした。

Rails:日時/時刻表示方法(設定)を変更する

Railsでは、Time::DATE_FORMATS というハッシュに時刻出力用のフォーマットがデフォルトで定義されているので、このハッシュに独自のフォーマットを追加する。

デフォルトは以下のように出力されます。

 Time.now.to_s
 => 2014-08-27 08:35:20 +0900 

1. time_formats.rbを作成してフォーマットを追加する

config/initializers配下にtime_formats.rbを作成して、デフォルトで定義されているフォーマット意外にいくつか追加してみる。

2. 試してみる

Time.now.to_s
=> "2014/08/27 08:36”

Time.now.to_s(:date)
=> "2014/08/27”

Time.now.to_s(:datetime)
=> "2014/08/27 08:37”

Time.now.to_s(:time)
=> "08:37:36”

Date.today.to_s
=> "2014/08/27"

viewで使うときは、以下のような感じで!

<p><%= project.created_at.to_formatted_s(:datetime) %></p>

Rails:pg gemをインストールできない

Herokuにアプリケーションをアップするために、DBをPostgreSQLに変えることに。
と思ったら、pgをインストールできなかった(´・Д・)」

※DBの変更の仕方は以前のブログに書いてます。
RailsでSQLiteをやめてPostgreSQLを使う - Hello world, I am kgmx.

#Gemfile
gem 'pg', '0.17.1'
$ bundle intall

Fetching gem metadata from https://rubygems.org/.........
Fetching additional metadata from https://rubygems.org/..
Resolving dependencies...
Using rake 10.3.2
Using i18n 0.6.11
Using json 1.8.1
Using minitest 5.4.0
Using thread_safe 0.3.4
Using tzinfo 1.2.2
Using activesupport 4.1.4
Using builder 3.2.2
Using erubis 2.7.0
Using actionview 4.1.4
Using rack 1.5.2
Using rack-test 0.6.2
Using actionpack 4.1.4
Using mime-types 1.25.1
Using polyglot 0.3.5
Using treetop 1.4.15
Using mail 2.5.4
Using actionmailer 4.1.4
Using activemodel 4.1.4
Using arel 5.0.1.20140414130214
Using activerecord 4.1.4
Using thor 0.19.1
Using railties 4.1.4
Using activerecord-session_store 0.1.0 from git://github.com/rails/activerecord-session_store.git (at master)
Using bcrypt 3.1.7
Using coderay 1.1.0
Using better_errors 1.1.0
Using debug_inspector 0.0.2
Using binding_of_caller 0.7.2
Using bundler 1.6.5
Using chunky_png 1.3.1
Using coffee-script-source 1.7.1
Using execjs 2.2.1
Using coffee-script 2.3.0
Using coffee-rails 4.0.1
Using fssm 0.2.10
Using sass 3.2.19
Using compass 0.12.7
Using hike 1.2.3
Using multi_json 1.10.1
Using tilt 1.4.1
Using sprockets 2.11.0
Using compass-rails 1.1.7
Using orm_adapter 0.5.0
Using warden 1.2.3
Using devise 3.2.4
Using haml 4.0.5
Using haml-rails 0.5.3
Using hashie 3.2.0
Using jbuilder 2.1.3
Using jquery-rails 3.1.1
Using method_source 0.8.2
Using newrelic_rpm 3.9.2.239
Using oauth 0.4.7
Using omniauth 1.2.2
Using omniauth-oauth 1.0.1
Using omniauth-twitter 1.0.1

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby -r ./siteconf20140825-20987-1vx7pma.rb extconf.rb --with-pg-config=/usr/local/bin/pg_config
Using config values from /usr/local/bin/pg_config
checking for libpq-fe.h... yes
checking for libpq/libpq-fs.h... yes
checking for pg_config_manual.h... yes
checking for PQconnectdb() in -lpq... no
checking for PQconnectdb() in -llibpq... no
checking for PQconnectdb() in -lms/libpq... no
Can't find the PostgreSQL client library (libpq)
*** 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=/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby
     --with-pg
     --without-pg
     --with-pg-config
     --with-pg-dir
     --without-pg-dir
     --with-pg-include
     --without-pg-include=${pg-dir}/include
     --with-pg-lib
     --without-pg-lib=${pg-dir}/
     --with-pqlib
     --without-pqlib
     --with-libpqlib
     --without-libpqlib
     --with-ms/libpqlib
     --without-ms/libpqlib

extconf failed, exit code 1

Gem files will remain installed in /var/folders/hm/spf_35s96v3cfvtc932bt60r0000gp/T/bundler20140825-20987-u7l8k0/pg-0.17.1/gems/pg-0.17.1 for inspection.
Results logged to /var/folders/hm/spf_35s96v3cfvtc932bt60r0000gp/T/bundler20140825-20987-u7l8k0/pg-0.17.1/extensions/universal-darwin-13/2.0.0/pg-0.17.1/gem_make.out
An error occurred while installing pg (0.17.1), and Bundler cannot continue.
Make sure that `gem install pg -v '0.17.1'` succeeds before bundling.

色々試してもできなかった。

$brew update
$brew uninstall
$brew install postgresql

最終的に以下でインストールできました。
理由は...わかりません。MacOS Xの問題?ちなみに今はMavericksです。

$ sudo su
sh-3.2# 
$ env ARCHFLAGS="-arch x86_64" gem install pg
Building native extensions.  This could take a while...
Successfully installed pg-0.17.1
invalid options: -f fivefish
(invalid options are ignored)
Parsing documentation for pg-0.17.1
Installing ri documentation for pg-0.17.1
Done installing documentation for pg after 1 seconds
1 gem installed
sh-3.2#

※DBの変更の仕方は以前のブログに書いてます。(しつこい。)
RailsでSQLiteをやめてPostgreSQLを使う - Hello world, I am kgmx.

Rails:文字列をカットして「...」で表示する(字数制限)

字数制限を設けて、その字数以上になる文字列はカットして、「hogehoge...」と表示したかったので、やってみた。

cssで横幅を指定してtext-overflow: ellipsis;を使ってやってもよかったけど、今回は字数制限ということにこだわりを...

application_helper.rbに以下を記述するだけです。

引数を渡し、使うときは、

puts cut_off("文字列", 文字数)

とする。

<%= cut_off("暑いけど今日も1日頑張るぞー", 10) %>
↓↓
暑いけど今日も1日頑...

と表示される。

Rails:LEFT JOINしてソートする

Rails:includesしてソートする - Hello world, I am kgmx.では
「別のテーブル(comment)のnameというカラムの値で降順にソートする」というのができなかったけど、できた!

やりたいこと:たくさんある本をコメントが多い順に上から並べる

■失敗

# Model.includes(:another_model).order("another_models.name desc")
@books = Book.includes(:comment).order("comments.name desc")

■成功

@books = Book    
    .joins("left join comments on books.id=comments.book_id")    
    .group("books.id")    
    .order("count(comments.id) desc")

本をコメントの多い順にソートすることができました。
でもleft joinがいまいちよくわからんです。

JavaScript:どのブラウザかをUserAgentで判定する

Androidはpositon:fixed;が効かないという問題に直面し、Androidかどうかを判別するコードを書いたのでメモ。

Androidかどうかがわかればよかったので、実際に使ったのは以下のコードです。
やったことは、「Androidでアクセスした時にbodyにandroidというクラスを振って、別のcssを読み込ませる。」
他のブラウザも判別したい場合は、if文を追加して細かく分岐させれば良いと思う。

JavaScript:クロージャを意識したコードを書く

「ボタンをクリックした回数を数える」というのを実装したところ、クロージャの概念を教えてもらいました。

1. 書いたコード

2. 教えてもらったコード

100%はまだわかっていない...