HABTM:无法创建资源

时间:2018-05-17 12:12:36

标签: ruby-on-rails activerecord foreign-keys rails-activerecord has-and-belongs-to-many

关注this tutorial我试图在搜索和列表模型之间创建多对多。

设置完所有内容后,我无法创建新搜索。 这是我得到的错误:

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回滚,以便向搜索迁移添加一个关于“term”的索引,从那时起就无法工作:(

提前致谢!

1 个答案:

答案 0 :(得分:1)

HABTM不需要将一个模型ID保留在另一个模型中。 在你的情况下

Search模型无需listing_idListing模型,无需search_id

我们将为此提供一个连接表(SearchesListings)。

从模型和数据库中删除validates: listing_id, uniqueness: true

然后它的工作原理。