サブドメインを取得するために、このレールキャストを多かれ少なかれ実装しました。
http://railscasts.com/episodes/221-subdomains-in-rails-3
うまく機能しますが、一致しないサブドメインをルート パスにリダイレクトする必要があります。
これは routes.rb 部分です:
match '/' => 'menus#show', constraints: { subdomain: /^(?!www$)(.+)$/i }
そして、これはmenus#showにあります:
# GET /menus/1
# GET /menus/1.json
def show
if !params[:id].nil?
@menu = Menu.find(params[:id])
else
if Shop.find_by_subdomain(request.subdomain).nil?
respond_to do |format|
format.html { redirect_to(root_path, :notice => I18n.t("misc.not_found")) }
return
end
else
@menu = Shop.find_by_subdomain(request.subdomain).menus.last
end
end
if !@menu.nil?
respond_to do |format|
format.html # show.html.erb
format.json { render json: @menu }
end
end
end
そのため、サブドメインを使用しない可能性を維持したいと考えています (そのため、params[:id] をチェックします。次に、サブドメインが存在するかどうかを確認し、そうでない場合はリダイレクトします。
現在、存在しないドメインを試しているときにこれを取得しているので、彼はまだメニューを表示しようとしていると思います:
undefined method `shop' for nil:NilClass
Extracted source (around line #1):
1: <h2>Menu <%= @menu.shop.name %></h2>
2: <br>
3: <%= render :partial => 'menu_show' %>