Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

ruby on rails - Where is the NoMethodError?

I'm using Rails 6.0.3.4 and I can't find the "NoMethodError in Ga::Districts#index":

undefined method `cases' - Did you mean? case class

In this line:

<% @district.cases.each do |case_data| %>

Here are my files:

District Model

class District < ApplicationRecord
  has_many :users
  has_many :cases
  belongs_to :state
end

Case Model

class Case < ApplicationRecord
  belongs_to :user
  belongs_to :diagnosis
  belongs_to :district

  scope :unconfirmed, -> { where(confirmed_at: nil) }
  scope :confirmed, -> { where.not(confirmed_at: nil) }
end

District Controller(/controllers/ga)

class Ga::DistrictsController < ApplicationController
  before_action :authenticate_user!
  before_action :current_user_ga?

  def current_user_ga?
    return if current_user.role == 'ga'
    redirect_to root_path
  end

  def index
    @district = District.includes(:cases).where(id: 1) 
    #I don't want to use a static ID, instead it should be the district_id of the current user.
  end
end

and the index.html.erb (views/ga/districts)

<h1>Total cases for</h1>

<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">Gender</th>
      <th scope="col">Birthdate</th>
      <th scope="col">Place of residence</th>
      <th scope="col">Diagnosis</th>
      <th scope="col">Confirmed at</th>
    </tr>
  </thead>

  <tbody>
    <% @district.cases.each do |case_data| %>
      <tr>
          <td><%= case_data.gender %></td>
          <td><%= case_data.birthdate %></td>
          <td><%= case_data.place_of_residence %></td>
          <td><%= case_data.diagnosis.illness %></td>
          <td><%= case_data.confirmed_at %></td>
      </tr>
    <% end %>

  </tbody>
</table>

I would really appreciate any kind of input!

question from:https://stackoverflow.com/questions/65927731/where-is-the-nomethoderror

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think where returns an array of records so you have to concatenate first in your query:

@district = District.includes(:cases).where(id: 1).first

Or even easier instead of using where you can use find:

Edit: I made a mistake using the find method, this should be the correct way to fetch the district:

@district = District.includes(:cases).find(1)

Also there is not a n+1 problem to fix when fetching only one record so you can safely remove the includes part of the query:

@district = District.find(1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...