При нажатии на кнопку Отправить моя форма приложения rails показывает сообщение об ошибке - PullRequest
0 голосов
/ 25 марта 2020

При нажатии submit button на моем form в форме. html .erb, оно не отправляется, и я получаю сообщение «Please review the problems below:», но в нем нет никаких проблем.

Может кто-нибудь объяснить мне, почему это происходит, и как я могу это исправить? Было бы очень признательно.

Please review the problems below:

schedule.rb

class Schedule < ApplicationRecord

    # Tenant Of
  belongs_to :account, :inverse_of => :schedules
  accepts_nested_attributes_for :account

  belongs_to :practitioner, :inverse_of => :schedules
  accepts_nested_attributes_for :practitioner

  has_many :bookings, :inverse_of => :schedule
  accepts_nested_attributes_for :bookings

  validates :start, uniqueness: { scope: :practitioner_id, message: "You have already made this time available" }

  amoeba do
    enable
    exclude_associations :bookings
  end

end

scheldules_controller. rb

class SchedulesController < ApplicationController
  before_action :set_schedule, only: [:show, :edit, :update, :destroy]

  # GET /schedules
  # GET /schedules.json
  def index
    @schedules = Schedule.all
  end

  # GET /schedules/1
  # GET /schedules/1.json
  def show
  end

  # GET /schedules/new
  def new
    @schedule = Schedule.new
  end

  # GET /schedules/1/edit
  def edit
  end

  # POST /schedules
  # POST /schedules.json
  def create
    @schedule = Schedule.new(schedule_params)

    respond_to do |format|
      if @schedule.save
        format.html { redirect_to @schedule, notice: 'Schedule was successfully created.' }
        format.json { render :show, status: :created, location: @schedule }
      else
        format.html { render :new }
        format.json { render json: @schedule.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /schedules/1
  # PATCH/PUT /schedules/1.json
  def update
    respond_to do |format|
      if @schedule.update(schedule_params)
        format.html { redirect_to @schedule, notice: 'Schedule was successfully updated.' }
        format.json { render :show, status: :ok, location: @schedule }
      else
        format.html { render :edit }
        format.json { render json: @schedule.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /schedules/1
  # DELETE /schedules/1.json
  def destroy
    @schedule.destroy
    respond_to do |format|
      format.html { redirect_to schedules_url, notice: 'Schedule was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def schedule_params
      params.require(:schedule).permit(:title, :start, :end, :practitioner_id, :account_id)
    end
end

index. html .erb

<p id="notice"><%= notice %></p>

<h1>Schedules</h1>

<table>

  <thead>
    <tr>
      <th>Title</th>
      <th>Start</th>
      <th>End</th>
      <th>Practitioner</th>
      <th>Account</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @schedules.each do |schedule| %>

    <tr>
      <td><%= schedule.title %></td>
      <td><%= schedule.start %></td>
      <td><%= schedule.end %></td>
      <td><%= schedule.practitioner_id %></td>
      <td><%= schedule.account_id %></td>
      <td><%= link_to 'Show', schedule %></td>
      <td><%= link_to 'Edit', edit_schedule_path(schedule) %></td>
      <td><%= link_to 'Destroy', schedule, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    </tr>
    <% end %>
  </tbody>

</table>

<br>

<%= link_to 'New Schedule', new_clinic_practitioner_schedule_path %>

new. html .erb

<h1>New Schedule</h1>

<%= render 'form', schedule: @schedule %>

<%= link_to 'Back', clinic_practitioner_schedules_path %>

_form. html .erb

<%= simple_form_for([:clinic, :practitioner, @schedule]) do |f| %>

<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

<div class="form-inputs">
  <%= f.input :title %>
  <%= f.input :start %>
  <%= f.input :end %>
  <%= f.input :practitioner_id %>
  <%= f.input :account_id %>
</div>

<div class="form-actions">
  <%= f.button :submit %>
</div>
<% end %>

Log

Started POST "/clinics/42/practitioners/16/schedules" for ::1 at 2020-03-25 08:39:28 +0100
Processing by SchedulesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ESSxZ+AjguVEae4E+vR1EthgkAX2SNZAYaHYAiE6Kza6mvWbr07MR+RXw5xRiT/1qii1zp8mtAB1LOR7g1oIMw==", "schedule"=>{"title"=>"Testing", "start(1i)"=>"2020", "start(2i)"=>"3", "start(3i)"=>"25", "start(4i)"=>"07", "start(5i)"=>"37", "end(1i)"=>"2020", "end(2i)"=>"3", "end(3i)"=>"25", "end(4i)"=>"07", "end(5i)"=>"37", "practitioner_id"=>"2", "account_id"=>"2"}, "commit"=>"Create Schedule", "clinic_id"=>"42", "practitioner_id"=>"16"}
  User Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 104 ORDER BY `users`.`id` ASC LIMIT 1
  ↳ /Users/kaspervalentin/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
   (0.2ms)  BEGIN
  ↳ app/controllers/schedules_controller.rb:30
  Account Load (0.8ms)  SELECT  `accounts`.* FROM `accounts` WHERE `accounts`.`id` = 2 LIMIT 1
  ↳ app/controllers/schedules_controller.rb:30
  Practitioner Load (2.0ms)  SELECT  `practitioners`.* FROM `practitioners` WHERE `practitioners`.`id` = 2 LIMIT 1
  ↳ app/controllers/schedules_controller.rb:30
  Schedule Exists (1.1ms)  SELECT  1 AS one FROM `schedules` WHERE `schedules`.`start` = '2020-03-25 07:37:00' AND `schedules`.`practitioner_id` = 2 LIMIT 1
  ↳ app/controllers/schedules_controller.rb:30
   (0.2ms)  ROLLBACK
  ↳ app/controllers/schedules_controller.rb:30
  Rendering schedules/new.html.erb within layouts/application
  Rendered schedules/_form.html.erb (26.5ms)
  Rendered schedules/new.html.erb within layouts/application (29.2ms)
  Rendered layouts/_header.html.erb (5.4ms)
  Rendered layouts/_footer.html.erb (0.8ms)
Completed 200 OK in 170ms (Views: 153.4ms | ActiveRecord: 4.8ms)

1 Ответ

0 голосов
/ 25 марта 2020

Это потому, что ваш экземпляр не go через правила проверки модели. Возможно, у вас есть belongs_to ассоциация в модели, которая по умолчанию требуется, если вы не даете опцию optional: true

Чтобы понять, что происходит, попробуйте сделать это перед вашей формой в вашем представлении

<%= @schedule.errors.full_messages %>

Таким образом, вы увидите, какие ошибки валидации присутствуют. (Но я почти уверен, что это потому, что вы забыли прикрепить его к практикующему и / или клини c

...