1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby on Rails [学習記録-第4章-]

Posted at

コントローラで受け取ったデータをビューに反映

  • コントローラのアクション内に定義したインスタンス変数(@つきの名前の変数)は、そのアクションが表示するビュー内で利用することができる。
  • Railsの見た目用のファイルであるerbファイルの中でRubyのコードを利用する場合、<%= %>という記述で囲う。
apps_controller.rb
class AppsController < ApplicationController

  def index
    @app = "プログラミング"
  end

end
index.html.erb
 <%= @app %>
  • 今、apps_controllerファイルを以下のように変えた場合、appsテーブルのレコードが、Appクラスのインスタンスとして代入される。
apps_controller.rb
  class AppsController < ApplicationController

    def index
      @apps = App.all #ここでいうAppは大文字単数形なのでモデルクラスのこと
    end

  end
  • @appをビューファイルで表示すると以下のようなかたちで記述できる。
index.heml.erb
<div class="contents row" >
  <% @apps.each do |app| %>
    <p><%= app.text %></p>
  <% end %>
</div>

simple_formatメソッド

  • <%= simple_format(引数) %>で定義する。改行は<br/>を付与、文字列を<p>で括るかたちで文字列を加工してくれる。
  • Railsでは主にviewでHTMLタグを出現させたりテキストを加工するために予めメソッドが用意されており、これらをまとめてヘルパーメソッドという。
  • 他にもform_tag(フォームを出現させるメソッド)やlink_to(aタグを出現させるメソッド)などがある。
index.heml.erb
  <div class="contents row" >
    <% @apps.each do |app| %>
      <div class="content_post" style="background-image: url(<%= app.image %>);">
        <%= simple_format(app.text) %>
        <span class="name"><%= app.name %></span>
      </div>
    <% end %>
  </div>
  • 上記では@appに入れたインスタンス変数を、eachメソッドの変数appに入れたもの。頭文字が小文字であることからわかるようにクラス名ではないので混乱しないように。

CSSファイル

  • ざっくりとビューファイル(HTMLファイル)ができたので、CSSファイルを用意する。
  • application.html.erbでCSSファイルの指定がされている。
  • cssファイルはapp/assets/stylesheets/というディレクトリに配置する。
  • application.html.erbのstylesheet_link_tagの部分にapplicationと書いてあるので、このHTMLからはapp/assets/stylesheets/application.cssというCSSファイルを読み込むことを示しています。
application.html.erb
  <head>
    <title>Pictweet</title>
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>
  </head>
  • application.cssを開くと以下のようになっている。(ディレクトリはapp/assets/stylesheets/にある。)
  • require_treeには引数として与えられたディレクトリ以下のcssファイルをアルファベット順に全て読み込むという意味がある。
  • 現在require_treeの引数には.(ドット)が渡されています。引数.(ドット)はカレントディレクトリを表す。つまり、この記述によってapp/assets/stylesheetsというディレクトリにあるcssファイルは全て読み込まれることになる。
application.css
/*
 ## 中略 ##
 *
 *= require_tree .
 *= require_self
 */
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?