【问题标题】:Submitting form_with (or form _for) with nested resources is routing to wrong controller提交带有嵌套资源的 form_with(或 form_for)是路由到错误的控制器
【发布时间】:2018-12-07 00:38:28
【问题描述】:

我正在尝试提交一个显示方法的表单。无论我做什么,它都不会转到正确的控制器并总是路由回 show 方法。问题是它应该转到 LeadsController create 方法,而不是 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 belongs_to 一个 :job_listing 和一个 Joblisting has_many :leads。

我已经尝试了我能找到的一切,但无论我做什么,结果都是一样的。 View console

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

【问题讨论】:

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


    【解决方案1】:

    检查您的表单没有嵌入到另一个表单中。

    【讨论】:

    • 感谢您的回复!我已经改变了,但问题是它应该去 LeadsController create 方法,而不是 JobListingsController show 方法。
    • 表单可能默认为get 方法。尝试指定form_with(model: [@job_listing, Lead.new], method: :post) 看看是否会改变操作。
    • 感谢您的回复,结果是我渲染的表单在 HTML 中的另一个表单内。这就是为什么它不尊重我告诉它提交的原因。它现在像冠军一样工作!
    • 感谢您提供有关实际问题的最新信息。为了其他有类似问题的社区成员的利益,我将更新此答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    相关资源
    最近更新 更多