Ruby添加到数据库

时间:2014-06-22 05:34:37

标签: ruby-on-rails ruby

我是Ruby的新手,我必须完成我的学校项目。我有问题,因为我们在14个人中制作了一个项目,每个人都有自己的一部分。我必须创建新的约会,但有人之前使用过这个,我不能再使用它了(我想从表单中添加这个简单)。请帮助我因为我现在被卡住了,我不想改变别人的代码。我从new51.html.erb渲染_form51.html.erb。也许我可以使用任何简单的重定向来创建51 ?;>但我不知道如何;(

EDITED: 现在解决但为什么应用程序创建总是空约会?

routes.rb中:

ZOZ::Application.routes.draw do

  resources :refferals do
    collection do
        get 'new51' 
    end
     member do
        get 'show'
  end
  end

  resources :appointments do 
    collection do
        get 'search' #17
        get 'search_result' #17
        get 'to_confirm' #17
        get 'search_not' #57
        get 'search_result_not' #57
        get 'add_or_edit_not' #57
        get 'searchdate'
        get 'searchd'
        get 'move'
        get 'new51'
        post :create51
    end
    member do
        put :confirm #17
        put :update_not #57
        get 'show51'
    end
  end

  resources :clinics do
  collection do 
        get 'index51'
    end
  member do
        get 'show51s'
  end
  end


  resources :doctors do
    collection do 
        get 'index51a'
        get 'index51'
        get 'search54'
        get 'search_result54'
        get 'show_harmonogram'
    end
    member do
        get 'show51s'
        get 'show51ss'
    end
  end


    resources :patients do
    collection do 
        get 'select51'
        get 'index51'
    end
    member do
        get 'show51s'
        get 'show51ss'
    end
  end

  get "welcome/index2"
  get "welcome/index"

  get 'appointments/create'
  get 'appointments/move' => 'appointments#move'
  post 'appointments/move' => 'appointments#doctors_list'
  get 'appointments/move/:id' => 'appointments#doctor_appointments', as: :doctor_appointments
  get 'appointments/change_appointment/:id' => 'appointments#change_appointment', as: :change_appointment
  get 'appointments/change_doctor_and_appointment/:id' => 'appointments#change_doctor_and_appointment', as: :change_doctor_and_appointment
  get 'appointments/success' => 'appointments#success'

  # The priority is based upon order of creation:
  # first created -> highest priority.

  # Sample of regular route:
  #   match 'products/:id' => 'catalog#view'
  # Keep in mind you can assign values other than :controller and :action

  # Sample of named route:
  #   match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
  # This route can be invoked with purchase_url(:id => product.id)

  # Sample resource route (maps HTTP verbs to controller actions automatically):


  # Sample resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Sample resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Sample resource route with more complex sub-resources
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', :on => :collection
  #     end
  #   end

  # Sample resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end

  # You can have the root of your site routed with "root"
  # just remember to delete public/index.html.
  root :to => 'welcome#index'

  # See how all your routes lay out with "rake routes"

  # This is a legacy wild controller route that's not recommended for RESTful applications.
  # Note: This route will make all actions in every controller accessible via GET requests.
  # match ':controller(/:action(/:id))(.:format)'
end

_form51.html.erb:

<%= form_for(@appointment) do |f| %>
  <% if @appointment.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@appointment.errors.count, "error") %> prohibited this appointment from being saved:</h2>

      <ul>
      <% @appointment.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :data_godzina_wizyty %><br />
  <%=
    options = { start_year: 2.year.from_now.year,
                end_year: 2013,
                include_blank: true,
                default: nil }
    f.datetime_select :data_godzina_wizyty, options
  %>
  <!--<input type="text" data-behaviour='datepicker' :data_wizyty > -->
  </div>
  <div class="field">
    <%= f.hidden_field :doctor_id, :value => Doctor.find(session[:current_doctor_id2]).id %>
  </div>
  <div class="field">
    <%= f.hidden_field :patient_id, :value => Patient.find(session[:current_patient_id]).id %>
  </div>
  <div class="actions">
    <%= submit_tag "Utworz wizyte" %>
  </div>
<% end %>

New51.html.erb:

<div id="container">
<center>
<h1>Nowa wizyta:</h1>
<p>Sprawdz poprawnosc ponizszych danych a nastepnie uzupelnij formularz.</p>

<h3>Dane lekarza:</h3> 
<p>
  <strong>Imię lekarza:</strong>
   <%= Doctor.find(session[:current_doctor_id2]).imie_lekarza %>
</p>

<p>
  <strong>Nazwisko lekarza:</strong>
   <%= Doctor.find(session[:current_doctor_id2]).nazwisko_lekarza %>
</p>
<p>
  <strong>Specjalizacja lekarza:</strong>
   <%= Doctor.find(session[:current_doctor_id2]).specjalizacja %>
</p>
<h3>Dane pacjenta:</h3> 
<p>
  <strong>Imie:</strong>
   <%= Patient.find(session[:current_patient_id]).imie %>
</p>
<p>
  <strong>Nazwisko:</strong>
  <%= Patient.find(session[:current_patient_id]).nazwisko %>
</p>
<p>
  <strong>Pesel:</strong>
  <%= Patient.find(session[:current_patient_id]).pesel %>
</p>
<%= render 'form51' %>

<%= link_to 'Wybierz innego lekarza', index51_doctors_path %>
</br>
</center>
</div>

Appointments_Controller:

class AppointmentsController < ApplicationController
  before_filter :load_appointment, only: [:show, :update, :edit, :destroy]
  before_filter :load_wizard, only: [:new, :edit, :create]



   def searchd
  end

    def move
    end

  def doctors_list
    @doctors = Doctor.where("imie_lekarza like ? or nazwisko_lekarza LIKE ? or specjalizacja LIKE ?", "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%")
  end

  def doctor_appointments
    @doctor = Doctor.find(params[:id])
    @appointments = @doctor.appointments
  end

  def change_appointment
    @appointment = Appointment.find(params[:id])
  end

  def change_doctor_and_appointment
    @doctors = Doctor.all
    @appointment = Appointment.find(params[:id])
  end

  def success
    @notice = flash[:notice]
  end

  def searchdate
    d = params[:date]
    data = Date.new(d["(1i)"].to_i, d["(2i)"].to_i, d["(3i)"].to_i)
    @appointments = Appointment.scoped 
    @appointments = @appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day)
  end


  def search_not
  end 

  def search_result_not

    #pacjent
    @patients = Patient.scoped
    @patients = @patients.where(pesel: params[:pesel])

    d = params[:date]
    if d["(1i)"] != "" and d["(2i)"]. != "" and d["(3i)"] != ""
        data = Date.new(d["(1i)"].to_i, d["(2i)"].to_i, d["(3i)"].to_i)
        @appointments = @patients.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day)
    else
        @appointments = @patients.first.appointments
    end

  end

  def add_or_edit_not
    session['last_search_not'] = request.env["HTTP_REFERER"]
    @appointment = Appointment.find(params[:id])
    @patient = Patient.find(@appointment.patient_id)
    if @appointment.doctor_id != nil
        @doctor = Doctor.find(@appointment.doctor_id)
    end
    if @appointment.refferal_id != nil
        @refferal = Refferal.find(@appointment.refferal_id)
    end
  end

  def update_not
    @appointment = Appointment.find(params[:id])
    @appointment.notatka = params[:notatka]
    if @appointment.save
      redirect_to session[:last_search_not], notice: 'Notatka zostala zapisana.'
    else
      redirect_to :back, notice: 'Niestety wystapil blad. Prosze sprubowac pozniej'
    end
  end


  def search
  end


  def new51
    @appointment = Appointment.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @appointment }
    end
  end

  def create51
    @appointment = Appointment.new(params[:patient])

    respond_to do |format|
      if @appointment.save
        format.html { redirect_to @appointment, notice: 'Szczegoy wizyty pomyslnie zmodyfikowane!' }
        format.json { render json: @appointment, status: :created, location: @appointment }
      else
        format.html { render action: "new" }
        format.json { render json: @appointment.errors, status: :unprocessable_entity }
      end
    end
  end

  def search_result
    d = params[:date]
    data = Date.new(d["(1i)"].to_i, d["(2i)"].to_i, d["(3i)"].to_i)
  #szukanie pacjenta
    @patients = Patient.scoped
    @patients = @patients.where(pesel: params[:pesel])

  if params[:imie] != ""
      @patients = @patients.where(imie: params[:imie])
   end

   if params[:nazwisko] != ""
      @patients = @patients.where(nazwisko: params[:nazwisko])
   end
   #szukanie doctora
   opcja = 0
   @doctors = Doctor.scoped
  if params[:imie_lekarza] != ""
      @doctors = @doctors.where(imie_lekarza: params[:imie_lekarza])
      opcja = 1
   end

   if params[:nazwisko_lekarza] != ""
      @doctors = @doctors.where(nazwisko_lekarza: params[:nazwisko_lekarza])
      opcja = 1
   end
   #zlaczenie
    @patient_appo = @patients.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day, potwierdzona: false)
   if opcja == 1
        @doctors_appo = @doctors.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day, potwierdzona: false)
        @appointments = @patient_appo & @doctors_appo
    else
        @appointments = @patient_appo
   end
  end

  def to_confirm
    session['last_search'] = request.env["HTTP_REFERER"]
    @appointment = Appointment.find(params[:id])
    @patient = Patient.find(@appointment.patient_id)
    if @appointment.doctor_id != nil
        @doctor = Doctor.find(@appointment.doctor_id)
    end
    if @appointment.refferal_id != nil
        @refferal = Refferal.find(@appointment.refferal_id)
    end
  end

  def confirm
    @appointment = Appointment.find(params[:id])
    @appointment.potwierdzona = true
    if @appointment.save
      #redirect_to :back, notice: 'Rejestracja zostala pomyslnie potwierdzona.'
      redirect_to session[:last_search], notice: 'Rejestracja zostala pomyslnie potwierdzona.'
    else
      redirect_to :back, notice: 'Niestety wystapil blad. Prosze sprubowac pozniej'
    end
  end

  def index
    @appointments = Appointment.all
  end

  def show
  end

  def new
    @appointment = @wizard.object
    @clinics = Clinic.all
    @doctors = Doctor.all
  end

  public
  def findDoctorViaClinic( clinic )
    return( (Clinic.find(  clinic   )).doctors.uniq )
  end
  helper_method :findDoctorViaClinic

  def findScheduleViaDoctor(d)
    s = Schedule.includes(:doctors_workplace).where(doctors_workplace_id: (DoctorsWorkplace.includes(:doctor).where(doctor_id: d)) ).where(taken: 0) 
    return s
  end
    helper_method :findScheduleViaDoctor


  def edit
  end

  def create
    @appointment = @wizard.object
    if @wizard.save 
     s = ( Schedule.find( @appointment.schedule.id ) )
     s.taken = true
     s.save
      redirect_to @appointment, notice: "Appointment saved!"
    else
      render :new
    end
  end

  def update
#    if @wizard.save
#      redirect_to @appointment, notice: 'Appointment was successfully updated.'
#    else
#      render action: 'edit'
#    end

    @appointment = Appointment.find(params[:id])
    @old_appointment = @appointment.dup
    respond_to do |format|
      if @appointment.update_attributes(params[:appointment])
        DefaultMailer.move_appointment(@appointment, @old_appointment).deliver
        format.html { redirect_to appointments_success_path, notice: 'Pomyslnie zmieniono termin.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @appointment.errors, status: :unprocessable_entity }
      end
    end

  end

  def destroy
    @appointment.destroy
    redirect_to appointments_url
  end

private

  def load_appointment
    @appointment = Appointment.find(params[:id])
  end

  def load_wizard
    @wizard = ModelWizard.new(@appointment || Appointment, session, params)
    if self.action_name.in? %w[new edit]
      @wizard.start
    elsif self.action_name.in? %w[create update]
      @wizard.process
    end
  end
end

日志:

    Started POST "/appointments/create51" for 127.0.0.1 at 2014-06-22 08:22:53 +0200
    Processing by AppointmentsController#create51 as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"kMxnErrH13opSkUPbg9hRM0Sy5JVwDCAbGRDNP5BSfc=", "appointment"=>{"data_godzina_wizyty(1i)"=>"2015", "data_godzina_wizyty(2i)"=>"1", "data_godzina_wizyty(3i)"=>"17", "data_godzina_wizyty(4i)"=>"16", "data_godzina_wizyty(5i)"=>"15", "doctor_id"=>"1", "patient_id"=>"1"}, "commit"=>"Utworz wizyte"}
      [1m[35m (0.0ms)[0m  begin transaction
      [1m[36mSQL (2.0ms)[0m  [1mINSERT INTO "appointments" ("clinic_id", "created_at", "data_godzina_wizyty", "data_wizyty", "doctor_id", "godzina_wizyty", "notatka", "objawy_choroby", "patient_id", "potwierdzona", "refferal_id", "schedule_id", "updated_at", "wymaga_Potwierdzenia") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)[0m  [["clinic_id", nil], ["created_at", Sun, 22 Jun 2014 06:22:53 UTC +00:00], ["data_godzina_wizyty", nil], ["data_wizyty", nil], ["doctor_id", nil], ["godzina_wizyty", nil], ["notatka", nil], ["objawy_choroby", nil], ["patient_id", nil], ["potwierdzona", nil], ["refferal_id", nil], ["schedule_id", nil], ["updated_at", Sun, 22 Jun 2014 06:22:53 UTC +00:00], ["wymaga_Potwierdzenia", nil]]
      [1m[35m (13.0ms)[0m  commit transaction
    Redirected to http://localhost:3000/appointments/30
    Completed 302 Found in 23.0ms (ActiveRecord: 15.0ms)


Started GET "/appointments/new51" for 127.0.0.1 at 2014-06-22 08:22:42 +0200
Processing by AppointmentsController#new51 as HTML
  [1m[35mDoctor Load (1.0ms)[0m  SELECT "doctors".* FROM "doctors" WHERE "doctors"."id" = ? LIMIT 1  [["id", 1]]
  [1m[36mCACHE (0.0ms)[0m  [1mSELECT "doctors".* FROM "doctors" WHERE "doctors"."id" = ? LIMIT 1[0m  [["id", 1]]
  [1m[35mCACHE (0.0ms)[0m  SELECT "doctors".* FROM "doctors" WHERE "doctors"."id" = ? LIMIT 1  [["id", 1]]
  [1m[36mPatient Load (0.0ms)[0m  [1mSELECT "patients".* FROM "patients" WHERE "patients"."id" = ? LIMIT 1[0m  [["id", 1]]
  [1m[35mCACHE (0.0ms)[0m  SELECT "patients".* FROM "patients" WHERE "patients"."id" = ? LIMIT 1  [["id", 1]]
  [1m[36mCACHE (0.0ms)[0m  [1mSELECT "patients".* FROM "patients" WHERE "patients"."id" = ? LIMIT 1[0m  [["id", 1]]
  [1m[35mCACHE (0.0ms)[0m  SELECT "doctors".* FROM "doctors" WHERE "doctors"."id" = ? LIMIT 1  [["id", 1]]
  [1m[36mCACHE (0.0ms)[0m  [1mSELECT "patients".* FROM "patients" WHERE "patients"."id" = ? LIMIT 1[0m  [["id", 1]]
  Rendered appointments/_form51.html.erb (13.0ms)
  Rendered appointments/new51.html.erb within layouts/application (22.0ms)
  Rendered welcome/_form.html.erb (1.0ms)
Completed 200 OK in 103.0ms (Views: 100.9ms | ActiveRecord: 1.0ms)

    Started GET "/appointments/30" for 127.0.0.1 at 2014-06-22 08:22:53 +0200
    Processing by AppointmentsController#show as HTML
      Parameters: {"id"=>"30"}
      [1m[36mAppointment Load (0.0ms)[0m  [1mSELECT "appointments".* FROM "appointments" WHERE "appointments"."id" = ? LIMIT 1[0m  [["id", "30"]]
      Rendered appointments/show.html.erb within layouts/application (2.0ms)
      Rendered welcome/_form.html.erb (1.0ms)
    Completed 200 OK in 80.0ms (Views: 77.0ms | ActiveRecord: 0.0ms)

2 个答案:

答案 0 :(得分:1)

您的问题来自您在表单上使用的网址。 您应该在_form51.html.erb上尝试这样做:

form_for @appointment, :url => url_for(:action => "create51") do |f| 

如果你rake routes | grep 'create51',你将拥有铁路路径。然后你也可以这样做:

form_for @appointment, :url => create51_path do |f|

(这里我假设命令给你create51作为路径)。

答案 1 :(得分:1)

<强>路线

哇你的路线真的是WET

确实需要阅读resourceful routing - 您routes文件中的每条路线都需要与特定的controller相关联(分开)来自root to和其他通配符)

无论是谁写了你的路线文件,都会带来大量的具体行动。坦率地说,这是一团糟,我强烈建议你通过&amp;删除你在那里的任何自定义动作。

资源路由在Rails docs中描述如下:

enter image description here

底线是你不应该为特定记录创建路线;您需要创建一个系统来处理应用程序将具有的不同进程

-

<强>表格

如果您没有在数据库中看到任何对象,则可能存在许多问题。但最重要的是你在部分中使用了@instance variable

据我所知,partials不会将@instance variables传递给他们的渲染过程。你必须通过local variables

#new.html.erb
<%= render "form51", locals: { appointment: @appointment } %>

#_form51.html.erb
<%= form_for appointment do |f| %>
   ...
<% end %>

-

老实说,有很多东西可以解决这个问题,如果你在这里的评论中寻求帮助将是最好的 - 所以我可以确切地指出需要修复的内容