LoginSignup
71
69

More than 5 years have passed since last update.

Rails4.1.0以降でPC,スマホ向けに自動的にページを切り替えて表示する

Posted at

Ruby on Rails 4.1.0以降でパソコンでアクセスした時,スマホでアクセスした時,タブレットでアクセスした時に表示を切り替える方法が簡単になったようなのでまとめます!

ちなみに今回はiPhone,iPadからアクセスする事を想定してます.
まず,適当にRailsのアプリを作ります.今回はtryvariantというアプリ名にします.

$ rails new tryvariant

その後,コントローラを作ります.
今回はIndexコントローラとします.

$ rails g controller Index

indexコントローラに次のコードを書き込みます.

app/controller/index_controller.rb
    before_action :detect_devise_variant  # 何でも良い?? --- (1)

    def index
    end

    private
        def detect_devise_variant  # (1)と同じ名前
            case request.user_agent
            when /iPad/
                request.variant = :tablet
            when /iPhone/
                request.variant = :mobile
            end
        end

あとは,スマホとタブレットに対応するビューを作成するだけです.
ただrequest.variantに設定したシンボルをファイル名に追加していくだけです.
例えば...

request.variant = :tablet

であれば,

app/views/index/index.html+tablet.erb
index.html+tablet.erb

とするだけです.
:mobileの時も同じ要領です.
ちなみに,request.variantに設定されていないuser_agentが返って来たら,index.html.erbが表示されます.

簡単ですが,こんな感じです.
before_actionにメソッドを書いているので,同じコントローラ内の全アクションに有効になるので,簡単に切り替えが出来て便利ですね!!

71
69
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
69