LoginSignup
7
5

More than 5 years have passed since last update.

Railsへbootstrapの適用

Last updated at Posted at 2016-05-22

2016年5月時点でのRailsへのbootstrapの適用方法

Rails初心者の私の私的メモ&時間を無駄にせずに、bootstrapを導入できるようになるまで。

開発環境

  • 実行日時 2016年5月22日
  • Cloud9
  • ruby 2.3.0p0
  • Rails 4.2.5

下準備

プロジェクトを作成して、ヴューなどを作っていくのだが、今回は面倒なのでscaffoldで実行

プロジェクトを作成

terminal
> $ rails new MyProject

scaffoldを作る

terminal
> $ rails g scaffold user name:string body:text

DBを作成

terminal
> $ rake db:migrate

サーバーを起動

terminal
rails s -p $PORT -b $IP

https://(サーバーアドレス)../usersにアクセスしNew Userから確認用に2~3新規投稿しておく

alt
alt

Gemの追加

Gemfileに追記する

Gemfile
gem 'less-rails'
gem 'therubyracer'
gem 'execjs'
gem 'twitter-bootstrap-rails'

Gemをインストールする

terminal
>bundle install

インストール後に警告が出た場合

terminal
.
.
.
Using web-console 2.3.0
Using turbolinks 2.5.3
Bundle complete! 16 Gemfile dependencies, 62 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.
Post-install message from twitter-bootstrap-rails:
Important: You may need to add a javascript runtime to your Gemfile in order for bootstrap's LESS files to compile to CSS. 

**********************************************

ExecJS supports these runtimes:

therubyracer - Google V8 embedded within Ruby

therubyrhino - Mozilla Rhino embedded within JRuby

Node.js

Apple JavaScriptCore - Included with Mac OS X

Microsoft Windows Script Host (JScript)

**********************************************

そんなときは、さっと入力

terminal
>gem install execjs

bootstrapの適用

プロジェクトにbootstrapを適用させる

terminal
>rails g bootstrap:install less

scaffoldで作られたuser、すなわち「Users」に対して、bootstrapのクラスを追加させる

terminal
>rails g bootstrap:themed Users

上記のコードを実行するとterminalに下記コードが表示されるが、bootstrapを適用させるのに、既存のファイルに上書きしてもいいですか?って意味なので[Ynaqdh]の後ろにyを入力してエンター(ターン!!)
何回か聞かれるけどその都度、y押してターン!

terminal
>rails g bootstrap:themed Users
Running via Spring preloader in process 3471
    conflict  app/views/users/index.html.erb
Overwrite /home/ubuntu/workspace/app/views/users/index.html.erb? (enter "h" for help) [Ynaqdh] y

上書きが終わったらサーバーを再起動。
再起動しないと下のようなエラーがでる

couldn't find file 'twitter/bootstrap' with type 'application/javascript'

レイアウト変更

bootstrapには全体のレイアウトを簡単に変更できる機能が備わっている

terminal
>rails generate bootstrap:layout application fluid -f

レスポンシブ
- rails generate bootstrap:layout application fluid
レスポンシブじゃないほう
- rails generate bootstrap:layout application fixed

これでviews/layout/application.html.erbに適用させたレイアウトが反映される

ちなみに、viewはbootstrapのおかげで非常に見にくくなっているので、simple_formというgemを入れるとすっきりする

参考サイト

bootstrap
bootstrap/git

bootstrapのデザインが飽きたらbootswatchというデザインテンプレートも扱えます。
bootswatch
bootswatch/git

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5