【问题标题】:HABTM: can't create a resourceHABTM:无法创建资源
【发布时间】:2018-05-17 12:12:35
【问题描述】:

按照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 回滚,以便在搜索迁移中添加一个关于“术语”的索引,因为:(

提前致谢!

【问题讨论】:

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


    【解决方案1】:

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

    Search 模型不需要listing_idListing 模型不需要search_id

    我们将为此创建一个连接表 (SearchesListings)。

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

    然后就可以了。

    【讨论】:

    • 不敢相信我错过了。非常感谢!
    猜你喜欢
    • 2014-03-08
    • 2014-08-02
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 2020-03-22
    • 2012-07-15
    • 2019-08-31
    相关资源
    最近更新 更多