Ruby не может выполнить маршрутизацию на сайт

#ruby-on-rails #ruby

#ruby-on-rails #ruby

Вопрос:

Я пытаюсь перечислить всех врачей в моем проекте, используя <%= link_to 'Registration to visit', doctors_index51_path %> , но я получаю сообщение об ошибке: Couldn't find Doctor with id=index51 Я добавил get «doctors / index51» в маршруты, и у меня есть что-то вроде этого в doctors_controller:

   def index51
    @doctors = Doctor.all

    respond_to do |format|
      format.html # index51.html.erb
      format.json { render json: @doctors }
    end
  end 
  

Routes.rb:

 ZOZ::Application.routes.draw do

  resources :refferals


  resources :clinics


  resources :doctors

  get "welcome/index2"

  get "welcome/index"

  get "patients/select51"

  get "patients/show51"

  get "refferals/new"


  # 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):
  resources :patients

  resources :doctors do
    collection do
      get 'index51'
    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
  

Помогите мне, пожалуйста, я новичок в Ruby, и я борюсь со своим проектом в школе 🙂

В выводе rake routes у меня есть: index51_doctors GET /doctors/index51 (.:format) doctors#index51

Ошибка:

 ActiveRecord::RecordNotFound in DoctorsController#show

Couldn't find Doctor with id=index51
Rails.root: D:/Studia/Bazy Danych/Projekt/Implementacja/ZOZ

Application Trace | Framework Trace | Full Trace
app/controllers/doctors_controller.rb:25:in `show'
Request

Parameters:

{"id"=>"index51"}
  

Комментарии:

1. Какой результат rake routes ?

2. Похоже, вы настроили маршрут участника, а не маршрут сбора. Что у вас есть в routes.rb?

3. Rake routes показывает мне, что у меня есть doctors_index51_path, я не знаю, что не так, потому что у меня то же самое с patients_select51_path, и проблем нет 🙂

4. @user3742883 можете ли вы опубликовать свои маршруты рейка в своем вопросе?

Ответ №1:

вероятно, это то, что вам нужно.

  resources :doctors do
    collection do
      get 'index51'
    end
  end
  

редактировать: (после публикации routes.rb)
комментарий к 4-му утверждению

#resources :doctors

Он определен дважды, не так ли?

Комментарии:

1. должен ли я изменить link_to, потому что теперь я получаю ошибку неопределенной локальной переменной или метода `doctors_index51_path’?:)

2. Хорошо, я очистил эту ошибку, потому что теперь это index51_doctors_path но теперь я вернулся к предыдущей ошибке Не удалось найти Doctor с id=index51

3. как выглядит ссылка? выполнить rake routes

4. <%= link_to ‘Регистрация посещения’, index51_doctors_path %>

5. обновите вопрос с помощью файла routes.rb и rake routes, а также ошибки

Ответ №2:

Это самый простой способ добиться того, чего вы хотите!

get "doctors/index51", to: "doctors#index51"

и то, что вы сделали, обычно работает на статических страницах!

Надеюсь помочь!

Ответ №3:

Просто просмотрел ваш файл маршрутов и заметил, что вы используете такие маршруты, как get «пациенты / select51» и get «пациенты / show51»

Что делают эти маршруты? выберите пациента с идентификатором 51 и покажите пациента с идентификатором 51? You are not making rails RESTful routes . Вам следует ознакомиться с документацией rails, чтобы получить лучшее представление о том, что именно происходит

Error: Couldn't find Doctor with id=index51 указывает, что rails рассматривает index51 как идентификатор.

Исправить:

У вас есть resources :doctors внутри вашего файла routes.rb, который создает семь разных маршрутов в вашем приложении, все они сопоставляются с контроллером doctors, например:

 GET /doctors    doctors#index   display a list of all doctors
GET /doctors/new    doctors#new return an HTML form for creating a new doctor
POST  /doctors  doctors#create  create a new doctor
GET /doctors/:id    doctors#show    display a specific doctor
GET /doctors/:id/edit   doctors#edit    return an HTML form for editing a doctor
PATCH/PUT   /doctors/:id    doctors#update  update a specific doctor
DELETE  /photos/:id doctors#destroy delete a specific doctor
  

и ниже у вас есть:

 resources :doctors do
 collection do
  get 'index51'
 end
end
  

который создает get /doctors/index51 doctors#index51 и конфликтует, поэтому вам нужно удалить предыдущий. Хотя я по-прежнему предлагаю придерживаться значений по умолчанию, но для этого потребуется создать индекс действия, а не index51

Комментарии:

1. @user3742883 Я знаю, что это не было проблемой, и я редактировал свой ответ для решения, но все же это не путь rails, и ваши маршруты не являются RESTful, вот и все, что я говорю 🙂

2. Я знаю, и вы, конечно, правы, потому что я должен использовать Ruby в проекте, никогда не встречал этого снова, и для меня все еще C # или C лучше, чем PHP или Ruby: P Теперь мне нужно закончить свой проект, поэтому я ищу помощи здесь, потому что вы зависимы от ruby: D