Создание динамического выпадающего меню, вызывающего ошибку загрузки в моем контроллере - PullRequest
0 голосов
/ 20 января 2019

Я обновляю свой код, чтобы перейти от статических выпадающих меню к динамически связанным выпадающим меню. Я следую некоторым инструкциям из онлайн-учебника, адаптируясь к моим потребностям, но отстала. Учебник, которому я следую, находится здесь .... https://rubyplus.com/articles/3691-Dynamic-Select-Menus-in-Rails-5

LoadError (Невозможно автоматически загрузить константу Job_category, ожидаемая C: /Users/User/Desktop/ServeandProtect/app/models/job_category.rb для ее определения):

app / views / jobs / list.html.erb: 22: in block in _app_views_jobs_listing_html_erb__816863472_104736972' app/views/jobs/listing.html.erb:16:in _app_views_jobs_listing_html_erb__816863472_104736972 '

** My View / HTML - первый выпадающий список обновлен для использования моделей **

<div class="row">
  <div class="col-md-3">

    <%= render 'job_menu' %>

    </div>
    <div class="col-md-9">
      <div class="panel panel-default">
        <div class="panel-heading">
          Listing
        </div>

        <div class="panel-body">
          <div class="container">

            <%= form_for @job do |f| %>

            <div class="row">
              <div class="col-md-4 select">
                <div class="form-group">
                  <%= f.label :job_category_id %><br />
                  <%= f.collection_select :job_category_id, Job_category.order(:job_category),
                   :id, :job_category, include_blank: true %>
                </div>
              </div>

              <div class="col-md-4 select">
                <div class="form-group">
                  <label>Job Type</label>
                  <%= f.select :job_type, [["Cleaning", "Cleaning"], ["Gardening", "Gardening"],
                  ["Rubbish Clearance", "Rubbish Clearance"], ["Removals", "Removals"],
                  ["Collection & Delivery", "Collection & Delivery"], ["Car Service & Repairs", "Car Service & Repairs"]],
                  id: "job_type", prompt: "Select...", class: "form-control" %>
                </div>
              </div>

              <div class="col-md-4 select">
                <div class="form-group">
                  <label>Frequency</label>
                  <%= f.select :recurrence, [["One Off", "One Off"], ["Daily", "Daily"],
                  ["Weekly", "Weekly"], ["Bi-Monthly", "Bi-Monthly"],
                  ["Once-Monthly", "Once-Monthly"]],
                  id: "recurrence", prompt: "Select...", class: "form-control" %>
                </div>
              </div>

            </div>

            <div><%= f.submit "Save", class: "btn btn-normal" %></div>

            <% end %>


          </div>
        </div>

      </div>
  </div>
</div>

** Мой контроллер **

class JobsController < ApplicationController

  before_action :set_job , except: [:index, :new, :create, :edit, :delete_image_attachment ]
  before_action :authenticate_user!, except: [:show]
  before_action :is_authorised, only: [:listing, :budget, :description, :photo_upload, :location,
    :update, :show, :delete, :featured, :premium ]

  # GET /jobs
  def index
    @jobs = Job.all
  end

  # GET /jobs/1
  def show
  end

  # GET /jobs/new
  def new
    @job = current_user.jobs.build
  end

  def listing
    #@job = current_user.job
  end

  # GET /jobs/1/edit
  def edit
  end

  def budget
  end

  # POST /jobs
  def create
    @job = current_user.jobs.build(job_params)

    if @job.save!
      redirect_to listing_job_path(@job), notice: 'Jobs dev was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /jobs/1
  # def update
  #   if @job.update(job_params)
  #     redirect_to @job, notice: 'Jobs dev was successfully updated.'
  #   else
  #     render :edit
  #   end
  # end

  def update
  #respond_to do |format|
    if @job.update(job_params)
      #format.html { redirect_to @job, notice: 'Post was successfully updated.' }
      #format.json { render :show, status: :ok, location: @job }
      flash[:notice] = 'Saved...'
    else
      #format.html { render :edit }
      #format.json { render json: @job.errors, status: :unprocessable_entity }
      flash[:alert] = "Something went wrong..."
    end
    redirect_back(fallback_location: request.referer)
  #end
end

  # DELETE /jobs/1
  def destroy
    @job.destroy
    redirect_to jobs_url, notice: 'Job was successfully destroyed.'
  end

  def delete
  end

  def featured
    #@job = current_user.job
  end

  def premium
    #@job = current_user.job
  end

  # DELETE job images
  def delete_image_attachment
    @image = ActiveStorage::Attachment.find(params[:image_id])
    @image.purge
    redirect_back(fallback_location: request.referer)
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_job
      @job = Job.find(params[:id])
    end

    def is_authorised
      redirect_to root_path, alert: "You don't have permission..." unless current_user.id == @job.user_id
    end


    # Only allow a trusted parameter "white list" through.
    def job_params
      params.require(:job).permit(:job_category, :job_type, :job_title, :job_description, :recurrence,
        :featured, :premium, :budget, images: []
      )
    end
end

** Мои модели **

[![class JobCategory < ApplicationRecord
  #attr_accessible :job_category

  #validates :job_category, :presence => true

  has_many :job_types
  has_many :jobs
end

class JobType < ApplicationRecord
  #attr_accessible :job_type

  #validates :job_type, :presence => true

  belongs_to :job_category
  has_many :jobs
end

class Job < ApplicationRecord
  belongs_to :user
  #belongs_to :job_category
  #belongs_to :job_type

  has_many_attached :images

  validates :job_category, presence: true
  validates :job_type, presence: true
  validates :recurrence, presence: true
  #validates :job_title, presence: true
  #validates :job_description, presence: true

end][1]][1]

** Ошибка **

enter image description here

enter image description here

1 Ответ

0 голосов
/ 20 января 2019

Ваша модель, вероятно, не названа Job_category, но JobCategory. Просто измените название вашей модели с вашего взгляда с

<%= f.collection_select :job_category_id, Job_category.order(:job_category),
               :id, :job_category, include_blank: true %>

до

<%= f.collection_select :job_category_id, JobCategory.order(:job_category),
               :id, :job_category, include_blank: true %>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...