【问题标题】:Rails root path based on user intput基于用户输入的 Rails 根路径
【发布时间】:2014-01-27 20:26:52
【问题描述】:

我需要让用户选择一个根路径(或获取)作为他创建的许多页面之一。这意味着,我希望能够创建页面“精彩页面”并将其设置为首页(http://example.com/)。

这有可能吗?我尝试将用户发送到固定操作并将用户重定向到所选操作,但这给我留下了这样的路线:http://example.com/page/8

我想要的结果是:http://example.com/ (而页面是用户选择的页面)。

任何帮助表示赞赏:)

编辑:我需要澄清一下。我希望用户能够选择页面或照片。这意味着我需要用户能够同时选择控制器和操作。

类似这样的:

constraints(Subdomain) do
    get "/" => '#{user_selected_controller}#{user_selected_action}/#{:id}'
end

上面的代码是完全错误的。但我认为它说明了我想要完成的事情。

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-4 routing


【解决方案1】:

您应该从控制器显式呈现页面视图。

config/routes.rb

root to: 'home#index'

控制器/home_controller.rb:

def index
  @page = #get fantastic page
  render 'pages/page', page: @page
end

http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-an-action-s-template-from-another-controller

【讨论】:

    【解决方案2】:

    我不是通过路由解决了这个问题,而是通过使用 users 表创建到 Pages 和 Galleries 的多态关联。像这样:

    首先创建多态关联

    # In my page model
    has_one :user, :as => :home
    
    # In my Gallery model
    has_one :user, :as => :home
    
    # In my User model
    belongs_to :home, polymorphic: true
    

    然后我在 users_controller 中使用它作为我的控制器:

    def home
        # Multitenant rails app. This refers to user who owns the subdomain visited.
        @user = current_tenant
    
        # This is not optimal, results in two queries.
        if @user.home_type.classify.constantize.exists?(@user.home_id)
    
            # This is the same as @page = Page.find(params[:id])
            instance_variable_set("@#{@user.home_type.downcase}", @user.home_type.classify.constantize.find(@user.home_id))
    
            # this is the same as render 'pages/show', layout: false
            render "#{@user.home_type.downcase.pluralize}/show", layout: false
        else
            redirect_to photos_path
        end
    
    end
    

    我的路线如下所示:

    # Set a page as the home screen
    post 'pages/set_home/:id' => 'pages#set_home', as: :set_home_page
    
    # User selected Home screen
    get "/" => 'users#home'
    

    设置主页:

    # In pages_controller
      def set_home
        @user = current_user
        @user.home = @page
        if @user.save
          redirect_to pages_path, notice: "Home screen set to #{@page.title}"
        else
          redirect_to pages_path, alert: "An error occured. Home not set."
        end
      end
    

    这样我可以通过 users.home 变量加载相关资源,同时使用正常路由到用户控制器主页操作。

    这可能是一个低效的解决方案,但它是我能想到的唯一一个。请随时提出改进建议:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2013-01-19
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多