1

I am new in Ruby and I have to finish my school project. I have problem because we make one project in 14 people, everyone has his own part. I have to create new appointment but someone used this before and I cannot use this again (I want to add this simple from form). Please help me because I am stuck now, I don't want change someone's code. I render _form51.html.erb from new51.html.erb. Maybe I can use any simple redirect to create51?;> But I don't know how ;(

EDITED: NOW SOLVED BUT why app create always empty appointment?

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

Logs:

    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)
11
  • How are you calling this method ? Commented Jun 22, 2014 at 5:39
  • I don't know because it is not my method and I don't want to use it, just to avoid them. It is why he added any wizard etc (...) in create method here. Commented Jun 22, 2014 at 5:42
  • Check if you @wizard variable is nil or not. What about ModelWizard.new(@appointment || Appointment, session, params) ? Is one of this variable nil ? Commented Jun 22, 2014 at 5:45
  • I didn't use this wizard before in my use case, it is used in other place on webpage by other person, it is possible to manipulate new51, create51 with avoiding this wizards? Commented Jun 22, 2014 at 5:57
  • This line before_filter :load_wizard, only: [:new, :edit, :create] tells you that you can call new51 and create51 without calling load_wizard Commented Jun 22, 2014 at 5:59

2 Answers 2

1

Routes

Wow your routes are really WET

You really need to read up on resourceful routing - every route you have in your routes file really needs to be associated to a particular controller (apart from root to and other wildcards)

Whoever wrote your routes file has laden it with massive numbers of specific actions. Frankly, it's a mess and I would highly recommend you go through & remove any custom actions you've got in there.

Resourceful routing is described in the Rails docs as thus:

enter image description here

Bottom line is you shouldn't be creating routes for specific records; you need to create a system to handle the different processes your application will have

--

Form

If you're not seeing any object created in your db, there could be a number of problems. The biggest, though, is your use of an @instance variable in your partial.

To the best of my knowledge, partials don't carry @instance variables through to their render process. You have to pass local variables:

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

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

--

Being honest, there's so much to fix with this, it will be best if you ask for help in the comments here - so I can pinpoint exactly what needs to be fixed

Sign up to request clarification or add additional context in comments.

6 Comments

I have changed to <%= render "form51", locals: { appointment: appointment } %> but nothing happened, still empty appointments goes to db, I can't change first line in _form51 because with this I removed my previous error and now action create51 is used :) I know there are not greate routes, it's why we have to complete project in Ruby, never met this before :) And we don't have any lessons about that:( It is implementation of use case and Ruby is choosen as language:(
Okay, so you say you don't receive the data. What happens? Does your form render in the partial? Where does the form submit to? can you post logs?
I don't know:) I have the same working code in create51 as in create before when I worked local alone. It goes to show.html.erb. I don't know where these logs are and how to show you:(
The logs should be in /log/[environment].log and will detail your requests. You should post the most recent requests
I almost finished my use case, just need to create appointment and validate later if there are already appointment in db with this date, time and if doctor works in that time ;)
|
1

You problem comes from the url you use on your form. You should try like this on your _form51.html.erb:

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

If you do rake routes | grep 'create51' you'll have the rails path. Then you can also do like this:

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

(here I suppose the command gave you create51 as path).

9 Comments

SyntaxError in Appointments#new51 Showing D:/p15/app/views/appointments/_form51.html.erb where line #1 raised: D:/p15/app/views/appointments/_form51.html.erb:1: syntax error, unexpected tASSOC, expecting keyword_end ...form_for(@appointment), :url => url_for(:action => "create51... Arrow shows second url
I have change that line to <%= form_for(@appointment), :url => url_for(:action => "create51") do |f| %>
My mistake, I put wrong brackets. I've updated the code.
What is the result of rake routes | grep 'create51' ?
Now I get : No route matches {:action=>"create51", :controller=>"appointments"} Really sorry for my simple question because now I have big mess in my head because of this Ruby :P
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.