gpt4 book ai didi

ruby-on-rails - Rails 4 STI 继承

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:51 25 4
gpt4 key购买 nike

我像这样成功地使用单表继承:

class Transaction < ActiveRecord::Base
belongs_to :order
end

class Purchase < Transaction
end

class Refund < Transaction
end

缩写/简化的 PurchaseController 如下所示:

class PurchaseController < TransactionController
def new
@transaction = @order.purchases.new(type: type)
end

def create
@transaction = @order.purchases.new secure_params
if @transaction.save
redirect_to @order
else
render :new
end
end
end

缩略/简化的购买模型如下所示:

class Purchase < Transaction
attr_accessor :cc_number, :cc_expiry, :cc_csv
end

我想做的是购买的不同变体,例如现金购买和支票购买。问题是我不确定如何调用该变体的模型。

例如:

class Cash < Purchase
attr_accessor :receipt_no
end

class CashController < TransactionController
def new
# This will use the Purchase.rb model so that's no good because I need the Cash.rb model attributes
@transaction = @order.purchases.new(type: type)

# This gives me the following error:
# ActiveRecord::SubclassNotFound: Invalid single-table inheritance type: Purchase is not a subclass of Cash
@transaction = Cash.new(type: 'Purchase', order: @order.id)
end
end

最佳答案

我不确定为什么它对你不起作用,这对我来说很好:

@order.purchases.new(type: "Cash") # returns a new Cash instance

如果您准备保存,您也可以将新的 Cash 推送给协会:

@order.purchases << Cash.new

或者你可以在Order中定义一个单独的关联:

class Order < ActiveRecord::Base
has_many :cashes
end

@order.cashes.new # returns a new Cash instance

关于ruby-on-rails - Rails 4 STI 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25901617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com