LoginSignup
7
10

More than 5 years have passed since last update.

Railsで、eachメソッドで配列の中身を展開するとき、任意の要素でスタイルを変える

Last updated at Posted at 2016-03-16

eachで回すとき、要素ごとにスタイルを変える

RubyのArrayクラスでは each と共に、 each_with_indexを提供しています。
indexとは要素の番号を表したもので、配列なので0から始まります。

今回はproductというモデルからデータをすべて持ってきて、4つだけ表示。それ以上のデータはもっと見るというリンクを作る。

といったデザインにします。つまり要素の4つ目だけにリンクをつける、ということです。


マイグレーションマイル、controller、viewは以下のとおりにします

20160225054421_create_products.rb
class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name,                 null: false
      t.integer :price,               null: false
      t.text :description,            null: false

      t.timestamps null: false
    end
  end
end

product_controller.rb
class ProductsController < ApplicationController

  def index
    @products = Product.all
  end

end
products/index.html.haml
  - @products.limit(4).each_with_index do |product,i|
    - if i == 3
      %p= product.name
      %p= "¥" + product.price.to_s
      %p= product.description    
      %a{href:""} もっと見る
    - else
      %p= product.name
      %p= "¥" + product.price.to_s
      %p= product.description

いろいろ応用がきくと思います♪(´ε` )

7
10
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
10