LoginSignup
0

More than 3 years have passed since last update.

Railsチュートリアル(第5章)

Posted at

はじめに

Railsチュートリアルの第5章が終わりました。
ポイントだけメモしておきます。

条件付きコメント

以下のように記述することで、Internet Explorerのバージョンが9以下の場合のみ、コメント内の処理が実行されます。

<!--[if lt IE 9]>
  <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js">
  </script>
<![endif]-->

リンク用のヘルパー

以下のように記述することで、リンクを記述することができます。
最終的にはaタグになります。

<%= link_to "テキスト", "URL" %>

CSSの記述

app/assets/stylesheets/ディレクトリ配下に置いたcssやscssファイルはアプリケーション全体で使用することができます。
また、bootstrapを使用する際は、ファイルの先頭に以下の内容を記述します。

@import "bootstrap-sprockets";
@import "bootstrap";

パーシャル

viewのコードをひとまとまりにして別ファイルにすることができます。これによって似たような記述を使いまわしたり、コードをわかりやすくすることができます。
パーシャルのファイル名は、_から始まる必要があります。

パーシャルをviewに組み込む場合は、以下のように記述します。

<%= render ”ファイルパス” %>

例えば、以下であればapp/view/layouts/_header.html.erbというファイルの内容を埋め込むことになります。
renderに記述する際は、先頭の_を外して記述します。

<%= render `layouts/header` %>

名前付きルート

routes.rbに記述したルートに名前を付けてリンク等に使うことができます。
以下のように記述します。

config/routes.rb
  root 'static_pages#home'
  get  '/help',    to: 'static_pages#help'
  get  '/about',   to: 'static_pages#about'
  get  '/contact', to: 'static_pages#contact'

rootで記述したルートには、root_pathでアクセスできます。
その他のルートは、上記の例だと、以下のようにアクセスできます。

  get  '/help',    to: 'static_pages#help'
  # help_pathによって'static_pages#help'にアクセスする

  get  '/about',   to: 'static_pages#about'
  # about_pathによって'static_pages#about'にアクセスする

  get  '/contact', to: 'static_pages#contact'
  # contact_pathによって'static_pages#contact'にアクセスする

これで、link_toを記述すると以下のようになります。

<%= link_to "About", about_path %>

また、以下のようにasを使って記述することで、名前付きルートの名前を変えることができます。

get  '/about',   to: 'static_pages#about', as: 'hoge'

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
0