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
いろいろ応用がきくと思います♪(´ε` )