その他
    ホーム技術発信DoRuby【Rails】プレビュー機能等作成の際によくつかう小技

    【Rails】プレビュー機能等作成の際によくつかう小技

    この記事はアピリッツの技術ブログ「DoRuby」から移行した記事です。情報が古い可能性がありますのでご注意ください。

    プレビュー機能って結構考慮する部分が多くて面倒だったりします。のでそこで自分がよく使っていることを紹介します。

    よくあるプレビュー機能の作り方

    ボタンにパラメーターをつけてアクション内のif文で分けたりする
    app/views/products/edit.slim

    = form_for @product do |f|
    ・
    ・
    ・
      = f.submit '保存', name: :submit, value: :save
      = button_tag 'プレビュー', name: :submit, value: :preview, formtarget: :_blank
    

    app/controllers/products_controller.rb

    def create
      if params[:submit] == 'preview'
        render 'show'
      else
        @product.save
    .
    .
    .
    end
    
    def update
      if params[:submit] == 'preview'
    .
    .
    .
    end
    

    煩雑すぎる!!
    のでアクションを分けましょう。
    でもformの向き先は1つなので通常では分けられないです。
    が、そこでjavascriptの登場です。

    おすすめなプレビュー機能の作り方

    app/controllers/products_controller.rb

    def preview
    .
    .
    .
    end
    

    app/views/products/edit.slim

    = form_for @product, html: { id: :product_form } do |f|



    = f.submit '保存'
    = link_to 'プレビュー', 'javascript:void(0)', id: :preview_button, data: { request_url: preview_product_path(@product)}

    app/assets/javascripts/products.coffee
    “`
    $main_form = $(‘#product_form’)
    $preview_button = $(‘#preview_button’)

    $preview_button.click ->
    original_action = $main_form.attr(‘action’)
    $main_form.attr(‘action’, $(this).data(‘request-url’))
    $main_form.attr(‘target’, ‘_blank’)
    $method = $main_form.find(“input[name=’_method’]”)
    $main_form.find(“input[name=’_method’]”).remove()
    $main_form.submit()
    $main_form.append($method)
    $main_form.attr(‘action’, original_action)
    $main_form.removeAttr(‘target’)
    “`
    ボタンを押したときにformの向き先を変えて仕舞えばいいのです!
    変えた後は元に戻すのを忘れずに。
    この方法はプレビュ−機能以外にも応用できるのでぜひ使ってみてください