omarshammas
omarshammas

Reputation: 631

Rails/Mongoid accepting nested attributes for models with inheritance

How do you accept nested attributes for models that use inheritance?

Rails 3.2, Mongoid 3.1

class User
    include Mongoid::Document
    include Mongoid::Timestamps

    field :name, type: String

    attr_accessible :name

    embeds_many :cards
    attr_accessible :cards_attributes
    accepts_nested_attributes_for :cards

end

The user class embeds many types of cards.

class Card
    include Mongoid::Document
    include Mongoid::Timestamps

    embedded_in :user
end

class HealthCard < Card
    field :number,      type: String

    attr_accessible :expiry_date, :number
end

class StudentCard < Card
    field :expiry_date, type: Date
    field :number,      type: String
    field :dept,        type: String


    attr_accessible :expiry_date, :number, :dept
end

The form below is used

= form_for @user do |user_form|

    = user_form.fields_for :health_cards, @health_card do |hc_form|
        = hc_form.text_field :number

    = user_form.submit 'Next'

On submit I observe the following params

{"user"=>{"health_cards"=>{"number"=>"6564 - 082 - 649 - AM"} }, "utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"C0DIKNbccfDQ=", "commit"=>"Next", "action"=>"update", "controller"=>"person_steps"}

Upvotes: 1

Views: 1134

Answers (1)

omarshammas
omarshammas

Reputation: 631

The problem was in the form, it should be user_form.fields_for :cards instead of :health_cards

Below is the corrected version

= form_for @user do |user_form|

    = user_form.fields_for :cards, @health_card do |hc_form|
        = hc_form.text_field :number

    = user_form.submit 'Next'

Upvotes: 1

Related Questions