【发布时间】: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