offer = Offer.first
Offer Load (0.3ms) SELECT "offers".* FROM "offers" ORDER BY "offers"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<Offer id: 1, name: "goa trip", description: "2 days", vendor_id: 1, created_at: "2016-10-12 08:57:14", updated_at: "2016-10-12 08:57:14">
2.2.3 :014 > offer.coupons.create(coupon_code: "1245343")
(0.1ms) begin transaction
(0.1ms) commit transaction
=> #<Coupon id: nil, coupon_code: "1245343", offer_id: 1, user_id: nil, created_at: nil, updated_at: nil>
2.2.3 :015 > Coupon.all
Coupon Load (0.1ms) SELECT "coupons".* FROM "coupons"
=> #<ActiveRecord::Relation []>
以下是模型方面的关系
class Vendor < ApplicationRecord
has_many :offers
end
class Offer < ApplicationRecord
has_many :coupons
belongs_to :vendor
end
class Coupon < ApplicationRecord
belongs_to :offer
belongs_to :user
end
这是架构
create_table "vendors", force: :cascade do |t|
t.string "name"
t.string "company_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "offers", force: :cascade do |t|
t.string "name"
t.string "description"
t.integer "vendor_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["vendor_id"], name: "index_offers_on_vendor_id"
end
create_table "coupons", force: :cascade do |t|
t.string "coupon_code"
t.integer "offer_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["offer_id"], name: "index_coupons_on_offer_id"
t.index ["user_id"], name: "index_coupons_on_user_id"
end
如果我以错误的方式使用这种关系,请告诉我。感谢
答案 0 :(得分:0)
正在运行
offer.coupons.create!(coupon_code: "1245343")
将显示验证错误。
我的假设是,您必须指定user_id
,因为您拥有并索引index_coupons_on_user_id
。
在Rails 5中 - 引用模型时,会自动创建foreign_key的索引。
你有2个foreign_keys:
offer_id
user_id
因此,创建了两个指数。