STI子类的模型创建和关联

时间:2014-02-09 16:58:32

标签: ruby-on-rails polymorphism subclass single-table-inheritance

我有一个具有一个Payoption的事件模型,它可以是使用STI子类的不同类型,如下所示:

class Event < ActiveRecord::Base
    has_one :payoption, dependent: :destroy
    accepts_nested_attributes_for :payoption    
end

class Payoption < ActiveRecord::Base
    belongs_to :event, :polymorphic => true

PAY_OPTION = ["BankPayoption", "CashPayoption"]
end

class BankPayoption < Payoption
    belongs_to :event
end

class CashPayoption < Payoption
    belongs_to :event
end

我在这样的控制器中创建一个事件和一个Cash / BankPayoption,在开发过程中仍然有一些硬编码和功能缺失:

def new
    @event = Event.new
    @event.build_payoption
end  

def create

    @event = Event.new(event_params)
    @event.user_id = current_user.id

    if params[:event][:payoption_attributes][:type] == "BankPayoption"
        @payoption = BankPayoption.new
        @payoption.phone = "0734176395"
        @payoption.event = @event
        @payoption.save
        @event.payoption = @payoption
    end

    @event.save
    redirect_to @event
end

Event和BankPayoption都被创建,BankPayoption获得了相关的事件ID,但事件根本没有获得任何Payoption ID,并且仍然是零。想象有STI /多态的问题,但无法弄清楚如何解决它。

提前致谢

1 个答案:

答案 0 :(得分:0)

我不确定这是不是你的问题。但是你的has_one关联中缺少as: :event

class Event < ActiveRecord::Base
    has_one :payoption, as: :event, dependent: :destroy
    accepts_nested_attributes_for :payoption    
end