如何通过模块获取控制器内的位置?

时间:2017-04-29 02:36:28

标签: ruby-on-rails

将我的控制器放入模块后:

module Admin
  class CampaignsController < AdminController # :nodoc:
    ...

    def create
      @campaign = Campaign.new create_params

      if @campaign.save
        render json: @campaign, status: :created, location: @campaign
      else
        render json: { errors: @campaign.errors.full_messages },
               status: :unprocessable_entity
      end
    end

    ...
  end
end

该位置不再有效:

#<NoMethodError: undefined method `campaign_url' for #<Admin::CampaignsController:0x007fbf36353f48>>

仅在我对其进行硬编码location: admin_campaign_url(@campaign)时才有效。

有更聪明的方法吗?

1 个答案:

答案 0 :(得分:2)

campaign_url辅助方法由路由控制:http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing

scope module: 'admin' do
  resources :campaigns
end

将创建campaign_url,它会调用Admin::CampaignsController,但同时,网址将为/campaigns,而不会/admin

您也可以尝试:

scope '/admin', module: 'admin' do
  resources :campaigns
end

您将拥有campaigns_url辅助方法,该方法将调用Admin::CampaignsController控制器,网址为/admin/campaigns