所有课程都在index.html.erb上显示,我试图通过点击查看更多来查看单个课程。根据我的理解,哪个应链接到节目路径,它显示个别课程。这是我需要的结果。
但是,在网址http://ruby-on-rails-102039.nitrousapp.com:3000/courses/rails上通过此错误(在此网址栏中是该课程的标题,每个新课程都会创建标题。
ActiveRecord::RecordNotFound in CoursesController#show
Couldn't find Course with 'id'=rails
Extracted source (around line #7):
def show @course = Course.find(params[:id]) end
课程控制器
class CoursesController < ApplicationController
def index
@courses = Course.all
end
def show
@course = Course.find(params[:id])
end
路线
devise_for :users
root 'signups#new'
resources :signups, only: [:new, :create]
resources :courses
Prefix Verb URI Pattern Controller#Action
root GET / signups#new
root GET / signups#new
signups POST /signups(.:format) signups#create
new_signup GET /signups/new(.:format) signups#new
courses GET /courses(.:format) courses#index
POST /courses(.:format) courses#create
new_course GET /courses/new(.:format) courses#new
edit_course GET /courses/:id/edit(.:format) courses#edit
course GET /courses/:id(.:format) courses#show
PATCH /courses/:id(.:format) courses#update
PUT /courses/:id(.:format) courses#update
DELETE /courses/:id(.:format) courses#destroy
index.html.erb
<div id="course-index">
<%@courses.each_slice(4) do|course| %>
<div class ="row">
<% course.each do |course|%>
<div class="col-md-3 col-sm-3">
<h3><%= course.title %></h3><br />
<h3><%= course. description %></h3><br />
<%= link_to 'View More', course_path(course), class:'btn btn-primary' %>
</div>
<%end%>
</div>
<%end%>
</div>
模型
class CreateCourses < ActiveRecord::Migration
def change
create_table :courses do |t|
t.string :title
t.string :desciption
t.integer :course_id
t.timestamps null: false
end
end
end
show.html.erb
<h1>Courses#show</h1>
<h1><%= @course.title %></h1>
<p> <%= @course.description %></p>
解决方案:所有这三个都在show方法中工作。我只是不明白为什么@course = Course.find(params [:id])。是因为我在模型中定义了这些列。
@course = Course.find_by(params[:title])
@course = Course.find_by(params[:course_id])
@course = Course.find_by(params[:description])
答案 0 :(得分:1)
@course = Course.find(params[:id])
按身份证号码查找课程,但您要传递标题而不是身份证号码。如果这就是你想保留它的方式
@course = Course.find_by(title: params[:id])
可能会做你想做的事情
答案 1 :(得分:0)
你可以试试这个:
#route.rb
resources :courses, params :title
此路线:course GET /courses/:id(.:format) courses#show
变成这样:course GET /courses/:title(.:format) courses#show
#controller.rb
#like said Tom Walpole you can do this:
@course = Course.find_by(title: params[:title])
#but I prefer this syntax:
@course = Course.find_by_title(params[:title])
如果您遇到错误,请在viex:course_path(course.title)