提交带有嵌套资源的form_with(或form_for)正在路由到错误的控制器

时间:2018-12-07 00:38:29

标签: ruby-on-rails ruby ruby-on-rails-5 ruby-on-rails-5.2

我正在尝试提交一种show方法。无论我做什么,都不会转到正确的控制器,并且始终会路由回show方法。问题是它应该转到LeadsController创建方法,而不是JobListingsController show方法。这是我的代码。

路线

resources :job_listings do 
  resources :leads
end

job_listings_controller

class JobListingsController < ApplicationController
  before_action :find_listing, only: [:show, :update, :edit, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
    @job_listings = JobListing.all.order("created_at DESC")
  end

  def new
    @job_listing = current_user.job_listings.build
  end

  def create
    @job_listing = current_user.job_listings.new(job_listing_params)

    respond_to do |format|
      if @job_listing.save
        format.html {redirect_to root_path}
      else
        format.js {render 'job_listings/new'}
      end
    end
  end

  def show
  end

  #...

  private

  #...

  def find_listing
    @job_listing = JobListing.find(params[:id])
  end
end

leads_controller

class LeadsController < ApplicationController
  include LeadsHelper
  before_action :authenticate_user!, only: [:index]
  before_action :find_admins, only: [:create]
  before_action :find_job_listing, only: [:create, :new]

  def index
    @leads = Lead.joins(:job_listing).order("created_at DESC")
  end

  def new
    @lead = Lead.new
  end

  def create 
    @lead = Lead.new(lead_params)

    respond_to do |format|
      if @lead.save
        send_emails_to_leads_admins
        set_cookie
        format.html {redirect_to root_path}
      else
        format.js {render 'leads/new'}
      end
    end
  end

  private

  def lead_params
    params.require(:lead).permit(:first_name, :last_name, :email, :file, :phone, :job_listing_id)
  end

  #...

  def find_job_listing
    @job_listing = JobListing.find(params[:job_listing_id])
  end
end

表格

<%= form_with( model: [@job_listing, Lead.new]) do |form| %>

我已经完成了正确的关联,一个Lead属于一个:job_listing,一个Joblisting has_many:leads。

我尽了一切可能,但无论我做同样的结果如何。 View console

任何提示或建议都会有所帮助!

1 个答案:

答案 0 :(得分:0)

检查您的表单未嵌入其他表单中。