HABTM: не могу создать ресурс - PullRequest
0 голосов
/ 17 мая 2018

После этого урока Я пытаюсь создать много-много разных моделей поиска и перечисления.

Когда все настроено, я не могу создать новый поиск.Вот ошибка, которую я получаю:

irb(main):001:0> Search.create(term: "baby")
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
Traceback (most recent call last):
        1: from (irb):1
NoMethodError (undefined method `listing_id' for #<Search id: nil, term: "baby", created_at: nil, updated_at: nil>
Did you mean?  listing_ids
               listing_ids=
               listings
               listings=)

Вот мои миграции:

class CreateJoinTableSearchesListings < ActiveRecord::Migration[5.1]
    def change
        create_join_table :searches, :listings do |t|
          t.index [:search_id, :listing_id]
          t.index [:listing_id, :search_id]
        end
    end
end

class CreateSearches < ActiveRecord::Migration[5.1]
    def change
        create_table :searches do |t|
          t.string :term, index: true

          t.timestamps
        end
    end
end

class CreateListings < ActiveRecord::Migration[5.1]
    def change
        create_table :listings do |t|
          ...
          t.string :title
          t.integer :listing_id
          ...

          t.timestamps
        end
    end
end

Вот мои модели:

class Search < ApplicationRecord
  has_and_belongs_to_many :listings, optional: true

  validates :listing_id, uniqueness: true
end

class Listing < ApplicationRecord
  has_and_belongs_to_many :searches, optional: true
  belongs_to :shop, optional: true

  validates :listing_id, uniqueness: true
end

Я пробовал это несколько минут назад, и этоработал отлично.Затем я откатился с STEP = 2, чтобы добавить в миграцию Searches индекс «term», не работающий с тех пор: (

Заранее спасибо!

1 Ответ

0 голосов
/ 17 мая 2018

HABTM не требует хранить один идентификатор модели внутри другого.В вашем случае

Search модель не должна иметь listing_id и Listing модель не должна иметь search_id.

Для этого у нас будет таблица соединений (SearchesListings).

Удалите validates: listing_id, uniqueness: true из моделей, а также из базы данных.

тогда это работает.

...