Rails 5如何将URL从company /:id / jobs /:id更改为jobs :: id

时间:2018-09-10 13:30:04

标签: routes ruby-on-rails-5

我有控制者:companiesjobs,公司has_many个工作,工作属于公司。

现在我这样写routes.rb

resources :companies do
    member do
      post :star
      delete :unstar
      get :destroys
      get :jobs
    end
    resources :jobs,except: [:index]
  end
  resources :jobs,only: [:index]

我的jobs_controller.rb是这样的:

class JobsController < ApplicationController
  before_action :logged_in_user,except: [:index,:show]
  before_action :set_company,except: [:index]
  def index
    @jobs = Job.all
  end

  def show
    @job = Job.find(params[:id])
  end

  def new
    @job = Job.new
  end

  def create
    @job = Job.new(job_params)
    @job.taggables.build
    @job.company_id = @company.id
    respond_to do |format|
      if @job.save
        format.html {
          redirect_to company_jobs_path(@company)
          flash[:success] = "Success"
        }
      else
        format.html { render :new }
      end
    end

  end


  private

  def set_company
    @company = Company.find(params[:company_id])
  end

  def job_params
    params.require(:job).permit!
  end
end

我可以使用以下网址获得公司的一份工作展示:

“ 127.0.0.1:3000/companies/4/jobs/1”

但是现在我只想按id获取作业网址,就像

“ 127.0.0.1:3000/jobs/1”

我怎么写routes.rb

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您只需要如下更改路线

resources :companies do
  member do
    post :star
    delete :unstar
    get :destroys
    get :jobs
  end
  resources :jobs,except: [:index, :show]
end
resources :jobs,only: [:index, show]

答案 1 :(得分:0)

尝试使用浅层嵌套吗?

resources :companies do
  member do
    post :star
    delete :unstar
    get :destroys
    get :jobs # <= Are you sure this should be here?
  end
  resources :jobs, shallow: true # <= This is new
end

此处的Rails文档链接:https://edgeguides.rubyonrails.org/routing.html#shallow-nesting