【问题标题】:Getting error (undefined method) for form_with为 form_with 获取错误(未定义的方法)
【发布时间】:2021-07-14 20:52:48
【问题描述】:

我有 _form.html.erb。在第一行代码中,它抛出了这个错误:

#ActionView::Base:0x00000000229750 的未定义方法“assessments_path” 你的意思是?资产路径

几点:

  1. 在路由中,“poweruser”是一个命名空间
  2. 在模型评估.rb 中是 不是文件夹 poweruser(因为我打算将它用于任何人都可以访问的其他页面,而不仅仅是 poweruser)。
  3. 有什么我缺少的想法吗?

代码如下:

<%= form_with(model: [@assessment], local: true) do |form| %>
  <%= render "shared/error_messages", resource: form.object %>

  <div class="form-group">
    <%= form.label :name %>
    <%= form.text_field :name, class: "form-control" %>
  </div>

<% end %>

这里是控制器

module Powerusers
  class AssessmentsController < ApplicationController
    before_action :authenticate_user!
    # before_action :set_assessment
    # before_action :set_assessment, only: [:set_assessment, :show, :edit, :update, :destroy]
    # Overwrite any of the RESTful controller actions to implement custom behavior
    # For example, you may want to send an email after a foo is updated.
    #
    # def update
    #   super
    #   send_foo_updated_email(requested_resource)
    # end

    def index
        @pagy, @assessments = pagy(Assessment.sort_by_params(params[:sort], sort_direction))
        # We explicitly load the records to avoid triggering multiple DB calls in the views when checking if records exist and iterating over them.
        # Calling @assessments.any? in the view will use the loaded records to check existence instead of making an extra DB call.
    @assessments.load
    end

    # GET /assessments/new
    def new
      @assessment = Assessment.new
      @assessment.assessment_sections.new
    end

这是assessment.rb(不是不是在子文件夹poweruser中)

class Assessment < ApplicationRecord
  belongs_to :company
  has_many :assessment_sections, inverse_of: :assessment
  has_many :questions, through: :assessment_sections

  accepts_nested_attributes_for :assessment_sections, reject_if: :all_blank,
                                allow_destroy: true
  accepts_nested_attributes_for :questions, reject_if: :all_blank,
                                allow_destroy: true
end

这里是路线

  # PowerUser
  authenticated :user, lambda { |u| u.admin? } do
    namespace :powerusers do
      resources :assessments do
        resources :assessment_sections do
          resources :questions
        end
      end
    end
 end

【问题讨论】:

    标签: html ruby-on-rails-6


    【解决方案1】:

    由于路由中有命名空间,因此需要使用 form_with 指定它

    <%= form_with(model: [:powerusers, @assessment], local: true) do |form| %>
    

    【讨论】:

    • 非常感谢。成功了 - 现在可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    相关资源
    最近更新 更多