LoginSignup
71
95

More than 5 years have passed since last update.

rails Viewでよく使うメソッド使い方具体例

Last updated at Posted at 2016-03-24

railsのView側で良く使うヘルパー系メソッドのよくある使い方中心に記載。主に自分参照用事例集。

  1. リンク(link_to)
  2. 画像 (image_tag)
  3. フォーム (form_for /form_tag)
  4. 関連モデルのフォーム (fields_for)
  5. テキストフィールドその他各種入力フィールド (text_field / password_field etc)
  6. ファイルアップロードフィールド (file_field / file_field_tag)
  7. プルダウン/セレクトボックス (select / select_tag / collection_select )
  8. チェックボックス (check_box / check_box_tag / collection_check_boxes )
  9. ラジオボタン (radio_button / radio_button_tag )
  10. hiddenフィールド (hidden_field / hidden_field_tag)

リンク link_to

基本の使い方

view
# 詳細に遷移ボタン。変数(message)渡し
<%= link_to "メッセージ詳細", edit_message_path(message) ,class:"btn btn-sm btn-warning glyphicon glyphicon-ok" %>

# 削除ボタン
<%= link_to "", message , method: :delete, data: {confirm: '削除してよろしいですか?'} ,class:"btn btn-sm btn-danger glyphicon glyphicon-remove" %>

# HTML属性を指定する
link_to "プロフィール", profile_path(@profile), class: "btn btn-large", id: "profile#{@profile.id}"
HTML側の表示
#=> <a class="btn btn-large" href="/profiles/1" id="profile1">プロフィール</a>

# クエリストリング(?=xxx)を追加する
link_to "プロフィール", profile_path(@profile, q: "list")
#=> <a href="/profiles/1?q=list">プロフィール</a>


# CSV, JSONなどリンクのフォーマットを指定する。
link_to "プロフィール", profile_path(@profile, format: 'csv')
#=> <a href="/profiles/1.csv">プロフィール</a>


# ブロックで特定要素を囲む
link_to "プロフィール", @profile do
  <strong><%= @profile.name %></strong>さんのプロフィール
end
#=> <a href="/profiles/1"><strong>鈴木</strong>さんのプロフィール</a>


# 条件によりリンクの表示有無を変える
# 管理者の場合、リンクを表示する。
link_to_if(current_user.admin?, "管理者用リンク", admin_path)

画像 image_tag

基本の使い方

image_tag("picture.png", alt:"home image", class: "menu_img")
# => <img alt="home image" class="main_img" src="/images/picture.png" />

画像の置き場所:絶対パスと相対パスのどちらでも指定可能。また、ファイルだけ指定した場合、assets/imagesフォルダからのパスとなる。

例: <%= image_tag 'picture.png' %>
#=> <img src="/images/picture.png" alt="Picture">

user_helperでのgravator表示メソッド化

module UsersHelper
    def gravatar_for(user, options = {size: 80})
        gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
        size = options[:size]
        gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
        image_tag(gravatar_url,alt: user.name, class:"gravatar")
    end
end

フォーム form_for

基本の使い方 ユーザ情報の更新(名前/email/パスワード/国)

view/user/index.html.erb
<%= form_for(@user, html:{class:"form-horizontal"}) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
    <div class="form-group">
        <%= f.label :name, class:"col-sm-2 control-label" %>
        <div class="col-sm-8">
            <%= f.text_field :name, class:'form-control'%>
        </div>
    </div>
    <div class="form-group">
        <%= f.label :email, class:"col-sm-2 control-label"  %>
        <div class="col-sm-8">
            <%= f.text_field :email, class:'form-control'%>
        </div>
    </div>
    <div class="form-group">    
        <%= f.label :password,class:"col-sm-2 control-label"  %>
        <div class="col-sm-8">
            <%= f.password_field :password , class:'form-control'%>
        </div>
    </div>
    <div class="form-group">    
        <%= f.label :password_confirmation,class:"col-sm-2 control-label"  %>
        <div class="col-sm-8">
            <%= f.password_field :password_confirmation , class:'form-control'%>
        </div>
    </div>
    <div class="form-group">    
        <%= f.label :country,class:"col-sm-2 control-label"  %>
        <div class="col-sm-2">
            <%= f.country_select :country , class:'form-control'%>
        </div>
    </div>
    <div class="form-group">
        <div class = "col-sm-offset-8 col-sm-2">
            <%= f.submit "変更する", class:"btn btn-sm btn-primary"%>
        </div>
    </div>

<% end %>
#form_forとform_tagの違い

form_for モデルの作成・更新などモデルに紐づくフォームを作成するために利用
form_tag 検索やレポート出力などモデルに紐付かないフォームのため

関連モデルのフォーム作成 fields_for

view
<%= form_for @user do |f| %>
  ...
  <%= f.fields_for :address do |address_fields| %>
    Street  : <%= address_fields.text_field :street %>
    Zip code: <%= address_fields.text_field :zip_code %>
  <% end %>
  ...
<% end %>

この使い方はまだやったこと無いからよくわからない。

テキストフィールド text_field

view
<%= form_for(@user) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

  <%= f.label :name %>
  <%= f.text_field :name, class:'form-control'%>

  <%= f.label :email %>
  <%= f.text_field :email, class:'form-control'%>

  <%= f.submit "create my account", class:"btn btn-large btn-primary"%>
<% end %>

テキストフィールド以外に下記も。
・メールアドレスフィールド(type="email") email_field / email_field_tag
・パスワードフィールド(type="password) password_field / password_field_tag
・検索フィールド(type="search") search_field / search_field_tag
・数値フィールド(type="number") number_field / number_field_tag
・テキストエリア text_area
<%= f.text_area:description, class:"form-control",rows:"4",placeholder:"詳細"%>

日付・時刻系

日付:date_field / date_field_tag
時間:time_field / time_field_tag
日付時刻:datetime_field
日付選択:time_select

<%= f.time_select :activated_at %>

ファイルアップロード file_field

model
class CreateContents < ActiveRecord::Migration
  def change
    create_table :contents do |t|
      t.string :upload_file_name
      t.binary :upload_file

      t.timestamps
    end
  end
end
view
<%= form_for(@content) do |f| %>
  <div class="field">
    <%= f.file_field :upload_file %>
  </div>
  <div class="actions">
    <%= f.submit "Upload" %>
  </div>
<% end %>
controller
def create
    upload_file = content_params[:upload_file]
    content = {}
    if upload_file != nil
      content[:upload_file] = upload_file.read
      content[:upload_file_name] = upload_file.original_filename
    end
    content[:password] = content_params[:password]
    @content = Content.new(content)
    respond_to do |format|
      if @content.save
        format.html { redirect_to @content, notice: 'Upload success' }
        format.json { render action: 'show', status: :created, location: @content }
      else
        @contents = Content.all
        format.html { render action: 'index' }
        format.json { render json: @content.errors, status: :unprocessable_entity }
      end
    end
  end

参考
http://qiita.com/kkabetani/items/d2c72394a490293277cc

プルダウン・セレクトボックス select /collection_select

検索用プルダウンの実装
※アイテムの一覧と関連するカテゴライズテーブルから検索

view/item/index

<%= search_form_for @q do |f| %>
<div class ="form-group">      
    <%= f.label :categorises_categorise_name_eq, "カテゴライズ",class:"control-label" %>
    <%= f.collection_select :categorises_id_eq, Categorise.all, :id, :categorise_name,{prompt: ""} ,{:class => "form-control"} %>
</div>
<div class ="form-group">           
<%= f.submit class:"btn btn-sm btn-primary" %> 
</div>

select2

検索可能なプルダウンを作成するjQueryプラグイン
スクリーンショット 2016-03-24 10.15.00.png

参考:http://ruby-rails.hatenadiary.com/entry/20141112/1415804076

チェックボックス check_box

単一のチェックボックス

view
<%= f.check_box :discontinued %> <%= f.label :discontinued, "販売停止" %>

複数のチェックボックス

view
<% Category.all.each do |category| %>
  <%= check_box_tag "product[category_ids][]", category.id, @product.categories.include?(category), id: "product_category_ids_#{category.id}" %>
  <%= label_tag "product[category_ids][#{category.id}]", category.name %>
<% end %>

ここいら辺は実際に実装していないので勉強不足。コントローラー側でもいろいろやる必要がありそう。

ラジオボタン radio_button

view
<%= f.label :rate %><br>
<%= f.radio_button :rate, 1 %> <%= f.label :rate_1, 1 %>
<%= f.radio_button :rate, 2 %> <%= f.label :rate_2, 2 %>
<%= f.radio_button :rate, 3 %> <%= f.label :rate_3, 3 %>
<%= f.radio_button :rate, 4 %> <%= f.label :rate_4, 4 %>
<%= f.radio_button :rate, 5 %> <%= f.label :rate_5, 5 %>

セレクトボックスのように配列を返すことで1行でラジオボタン複数個作れるらしい。

view
<%= f.collection_radio_buttons :maker_id, Maker.all, :id, :name %>

この辺も実際に実装したら追記しています。

hiddenフィールド hidden_field

レコードに対してお気に入り登録のフォームだが、モデルにはmicropost_idとuser_idを登録する必要があるので、hidden_fieldにしている。見かけ上はボタンしか見えない。

views/favorite_microposts/_favorite_micropost.html.erb
<%= form_for(current_user.favorite_microposts.build) do |f| %>
  <div>
    <%= hidden_field_tag :micropost_id, micropost.id %>
    <%= hidden_field_tag :user_id, current_user.id %>

  </div>
  <%= f.submit "Favorite", class: "btn btn-primary" %>

<% end %>

何故か、上記でうまく行かなかった(valueの指定で)ので、下記の書き方にしたら通った。
ポイントは、value => params[:id] とする点。

views
<%= form_for(@classify_relation, html:{class:"form-inline"}) do |f| %>
      <%= f.hidden_field :disease_id, :value => params[:id] %>
      <div class="form-group">
          <label>分類:</label>
          <%= f.collection_select:disease_classify_id, DiseaseClassify.all, :id, :classify_name,{prompt: ""}, {class:"form-control"}%>

      </div>
      <div class="form-group">
        <%= f.submit class:"btn btn-sm btn-primary center-block"%>
      </div>
<% end %>
71
95
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
71
95