NameError (неинициализированная константа Search :: Listings) Rails - PullRequest
0 голосов
/ 01 ноября 2018

Я просмотрел все сообщения об ошибках, подобных этой, и ни одна из них не похожа на мою. Я получаю сообщение об ошибке 'uninitialized constant Search::Listings' всякий раз, когда пытаюсь использовать свою ассоциацию has_many из поиска в список (это имена классов) в виде search.listings.count в _search_list.html.erb в каталоге / app / views / search.

Да, имена файлов: search.rb и list.rb и находятся в app / models.

Вот код для каждого класса и файл, в котором я запускаю код:

listing.rb

    # == Schema Information
#
# Table name: listings
#
#  id               :integer          not null, primary key
#  description      :text
#  price            :float
#  pricing          :string
#  title            :string
#  url              :string
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#  listings_poll_id :integer
#
# Indexes
#
#  index_listings_on_listings_poll_id  (listings_poll_id)
#

class Listing < ApplicationRecord
  has_many :listing_searches
  has_many :searches, through: :listing_searches
  has_many :users, through: :searches
end

search.rb:

# == Schema Information
#
# Table name: searches
#
#  id         :integer          not null, primary key
#  keywords   :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  user_id    :integer
#
# Indexes
#
#  index_searches_on_user_id  (user_id)
#

class Search < ApplicationRecord

  belongs_to :user
  has_many :listing_searches
  has_many :listings, through: :listing_searches

  # Validations done before saving.
  validates_presence_of :keywords
  validate :validate_keywords

  def validate_keywords
    entry = Search.find_by(user_id: user_id, keywords: keywords)
    if entry
      errors.add(:keywords, "Those keywords are already being used by you.")
    end
  end
end

listing_search.rb:

# == Schema Information
#
# Table name: listing_searches
#
#  id         :integer          not null, primary key
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  listing_id :integer
#  search_id  :integer
#
# Indexes
#
#  index_listing_searches_on_listing_id  (listing_id)
#  index_listing_searches_on_search_id   (search_id)
#
class ListingSearch < ApplicationRecord
  belongs_to :searches
  belongs_to :listings
end

_search_list.html.erb:

<% @searches.each do |search| %>
  <tr>
    <td><%= search.keywords %></td>
    <td><%= search.listings.count %></td>  --This line here is the cause
    <td><%= link_to 'Show', search %></td>
    <td><%= link_to 'Edit', edit_search_path(search) %></td>
    <td><%= link_to 'Destroy', search, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

Я попытался переместить код в контроллер поиска, и я получил ту же ошибку.

Я попытался добавить 'source' в ассоциации has_many.

Я попытался указать добавление опции 'class' к ассоциациям.

ПРИМЕЧАНИЕ. Я использую Ruby Mine для редактирования кода (запускаемой командной строки) и замечаю, что в среде IDE говорится «Невозможно найти связанную модель Rails для поля ассоциации ': lists" », но я читал, что это ошибка IDE, поэтому я не беспокоюсь об этом.

1 Ответ

0 голосов
/ 01 ноября 2018

Пожалуйста, попробуйте использовать единственное число в принадлежащем_списке list_search.rb

belongs_to :search belongs_to :listing

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...