从网址获取ID并使用它从表格中获取特定数据

时间:2019-06-11 21:10:28

标签: ruby-on-rails ruby ruby-on-rails-4 rubygems ruby-on-rails-5

我正在做一个研究项目。如何从URL获取ID并将其传递给控制器​​以从表中获取特定数据

我尝试过的一些代码 我现在收到此错误,没有ID找不到Major

控制器:

class MajorsController < ApplicationController
  before_action :set_major, only: [:show, :edit, :update, :destroy]

  # GET /majors
  # GET /majors.json
  def index
    @majors = Major.all
  end

  # GET /majors/1
  # GET /majors/1.json
  def show
    @majors = Major.find(params[:major_id])
    @courses = Course.all
  end

这是我的路线

Rails.application.routes.draw do
  get 'home/index'
  get 'home/contactUs'
  resources :courses
  resources :majors
  resources :sciences
  get '/majors/:id', to: 'majors#show', as: 'Major'
  root 'home#index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

显示

<p id="notice"><%= notice %></p>

<p>
  <strong>Name:</strong>
  <%= @major.name %>
</p>

<p>
  <strong>Description:</strong>
  <%= @major.description %>
</p>

<p>
  <strong>Science:</strong>
  <%= @major.science.name %>
</p>
<p>
  <strong>Number of courses:</strong>
  <%= @major.courses.count %>
</p>

<table class="table table-hover">
  <thead>
  <tr>
    <th>Name</th>
    <th>Description</th>
  </tr>
  </thead>

  <tbody>

  <% @major.course.each do |m| %>
    <tr>
      <td><%= m.name %></td>
      <td><%= m.description %></td>
    </tr>
  <% end %>
  </tbody>
</table>
<%= link_to 'Edit', edit_major_path(@major) %> |
<%= link_to 'Back', majors_path %>


我希望输出是我仅有的两门课程,但它们全部输出

1 个答案:

答案 0 :(得分:0)

通过添加@KonstantinStrukov所说的路线来解决问题 编辑节目

  <% @major.courses.each do |m| %>
    <tr>
      <td><%= m.name %></td>
      <td><%= m.description %></td>
    </tr>
  <% end %>

Rotes文件

Rails.application.routes.draw do
  get 'home/index'
  get 'home/contactUs'
  resources :courses
  resources :majors
  resources :sciences
  get '/majors/:id', to: 'majors#show', as: 'Major'
  root 'home#index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

控制器

  def show
    @majors = Major.where(params[:id])
    @courses = Course.all
  end