У меня есть небольшой сайт Rails с двумя контроллерами инструкторы и запросы. инструкторы доступны администратору сайта только для управления ими и управления ими (все методы аутентифицированы с помощью устройства). Второй контроллер инструкторы - это то, как посетители посещают сайт для просмотра перечисленных инструкторов и создают запросы для инструктора, которого они выбирают. У меня возникли проблемы при создании новых запросов, которые должны сохранить имя, телефона и электронной почтысообщения, а также выбранный instructor_id из запроса шоу-страницы. Надеюсь, что мое описание будет ясным.Rails неопределенный метод `model_name 'для nil: NilClass
Спасибо.
запрашивает контроллер
class RequestsController < ApplicationController
def index
if params[:search].present?
@instructors = Instructor.near(params[:search], 50)
else
# Shows all listed instructors by the created date.
@instructors = Instructor.order('created_at DESC')
end
end
def show
@instructor = Instructor.find(params[:id])
end
def new
@request = Request.new
end
def create
@request = Request.new(request_params)
#@request = Request.new(request_params)
if @request.save
flash[:success] = "Request has been submited!"
else
flash[:alert] = "Something is went wrong!"
end
end
private
def request_params
params.require(:request).permit(:name, :email, :phone, :message)
end
end
просит показать
<header><h1 class="display-4"><%= @instructor.name %></h1></header>
<h3>Address: <%= @instructor.address %></h3>
<h3>Car Model: <%= @instructor.car %></h3>
<hr>
<%= simple_form_for(@instructor, :url =>{ :action => "create" }) do |f| %>
<%= f.input :name, label: "Your name" %>
<%= f.input :email %>
<%= f.input :phone, label: "Phone number" %>
<%= f.input :message, as: :text %>
<br>
<%= f.button :submit, class: "btn btn-danger" %>
<% end %>
<br>
<br>
инструкторов контроллер
class InstructorsController < ApplicationController
# Admin is required to login to access any action on this controller
before_action :authenticate_admin! # except: [:action, :action] to unlock any action
def index
@instructors = Instructor.order('created_at DESC')
end
def show
find_instructor
end
def new
@instructor = Instructor.new
end
def update
find_instructor
if @instructor.update(instructor_params)
redirect_to @instructor
flash[:notice] = "Instructor changes has been saved."
else
render 'edit'
end
end
def create
@instructor = Instructor.new(instructor_params)
if @instructor.save
flash[:notice] = "Instructor has been saved!"
redirect_to instructors_path
else
render 'new'
flash_error('New instructor hasn\'t been saved.')
end
end
def edit
find_instructor
end
def destroy
find_instructor
if @instructor.destroy
redirect_to root_path
flash[:notice] = "The instructor has been deleted."
else
flash_error('Instructor hasn\'t been deleted.')
end
end
private
def flash_error(message) # Takes the of the error message as an argument
flash[:alert] = "Something went wrong!, #{message}
Please make sure you submitting valid data and try again"
end
def find_instructor
@instructor = Instructor.find(params[:id])
end
def instructor_params
params.require(:instructor).permit(:name, :car, :address, :manual, :auto)
end
end
flash_error('Instructor hasn\'t been deleted.')
end
end
private
def flash_error(message) # Takes the of the error message as an argument
flash[:alert] = "Something went wrong!, #{message}
Please make sure you submitting valid data and try again"
end
def find_instructor
@instructor = Instructor.find(params[:id])
end
def instructor_params
params.require(:instructor).permit(:name, :car, :address, :manual, :auto)
end
end
инструктор модель
class Instructor < ApplicationRecord
has_many :requests
geocoded_by :address
after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
end
запрос модель
class Request < ApplicationRecord
belongs_to :instructor
end
путь, более полезный, чем сброс вашего кода, будет показывать, что говорит об ошибке. Обратите внимание, что нигде в вашем коде вы не вызываете '.model_name' –
Можете ли вы разместить здесь ошибку? – Pramod
Нет кода для установления связи между запросом и инструктором. Вы также передаете '@ teacheror' в' simple_form_for', где вы, похоже, собираетесь создать 'Request', а не' Instructor'. Пожалуйста, уточните сообщение об ошибке и действие, которое запускает его. – Owen