没有ID找不到课程

时间:2019-04-20 09:17:14

标签: ruby-on-rails

当我尝试访问app / views / companies / courses / show.html.erb(在app / views / companies / courses / new.html.erb之后重定向)时,Rails服务器说找不到课程没有ID。

此外,当我在Rails控制台上运行Course.all时,这些课程具有正确的ID,正确的描述和正确的公司ID,但没有名称属性。

应用/控制器/公司/ courses_controller:

class Companies::CoursesController < ApplicationController
  before_action :authenticate_company!

  def new
    @course = Course.new
  end

  def create
    @course = current_company.courses.create(course_params)
    if @course.save
      redirect_to companycourse_path(:course => @course.id)
    else
      render 'new'
    end
  end

  def show
    @course = current_company.courses.find(params[:id])
  end

  def index
    @courses = current_company.courses.all
  end

  private

  def course_params
    params.require(:course).permit(:title, :description)
  end
end

App / models / course.rb:

class Course < ApplicationRecord
  belongs_to :company
end

App / models / company.rb:

class Company < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :courses
end

Config / routes.rb:

Rails.application.routes.draw do
  devise_for :companies
  devise_for :users
  root 'static_pages#home'
  get 'users/:id' => 'users#show'
  resources :users, only: [:show]
  get 'companies/:id' => 'companies#show'
  resources :companies, only: [:show] do
    resources :courses, only: [:show,:new,:create,:index]
  end

  devise_scope :user do
    get 'signup', to: 'users/registrations#new'
    get 'login', to: 'users/sessions#new'
  end

  devise_scope :company do
    get 'companysignup', to: 'companies/registrations#new'
    get 'companylogin', to: 'companies/sessions#new'
    get 'newcourse', to:'companies/courses#new'
    post 'newcourse', to:'companies/courses#create'
    get 'companycourse', to:'companies/courses#show'
    get 'companycoursesindex', to:'companies/courses#index'
  end

end

1 个答案:

答案 0 :(得分:0)

不久前,我在构建应用程序时遇到了类似的问题,而问题出在控制器上。

在您的route.rb中,我将添加resources :companies, :has_many => :courses。还将在models / course.rb中向您的课程模型添加一个验证,以确保将其保存到数据库时,您的对象具有标题: class Course < ApplicationRecord belongs_to :company validates :title, presence: :true end

也可以尝试使用此代码或您在courses_controller.rb中的某些行代替当前的代码:

    def create
     @company = find_company
     @course = Course.new(course_params)
     @course.company_id = current_company.id
    if @course.save
     your conditions here
    else
     your conditiona here
    end
   end 

   private
    def find_company
     params.each do |name, value|
      if name == 'company_id'
        return @company = Company.find(value.to_i)
      end
     end
    nil
    end

希望对您有帮助。