0

I have an Event model that has one Payoption which can be of different types using STI subclasses like this:

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

I'm creating an Event and a Cash/BankPayoption in the same controller like this, still some hardcoding and missing functionally while developing:

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

Both the Event and BankPayoption gets created and BankPayoption gets the corrent Event ID however the Event doesn't get any Payoption ID at all and remains nil. Figured there's issues with the STI/polymorphism but can't figure out how to solve it.

Thanks in advance

Oskar Eriksson
  • 845
  • 1
  • 9
  • 28

1 Answers1

0

I am not sure if this is your problem. But you are missing as: :event, in your has_one association.

class Event < ActiveRecord::Base
    has_one :payoption, as: :event, dependent: :destroy
    accepts_nested_attributes_for :payoption    
end
usha
  • 28,973
  • 5
  • 72
  • 93
  • Thanks for your answer. This gives me an "unknown attribute: event_type" at the @event.build_payoption line in the "new" method (added that in my post). – Oskar Eriksson Feb 09 '14 at 20:50
  • Did you really want a `polymorphic association` on `payoption`? if not get rid of `:polymorphic => true` – usha Feb 09 '14 at 23:35