Leon
Leon

Reputation: 161

Text field in Rails stores string instead of Hash

I am designing a controller that handles the receipts for my E-commerce site. This is what the JSON params look like:

{
"receipt": {
    "items": {
        "item1": {
            "price": "22.11",
            "quantity": "2",
            "name": "Name",
            "discount": 0.04
        },
        "item2": {
            "price": 12.11,
            "quantity": 1,
            "name": "Name"
        },
        "item3": {
            "price": 21.11,
            "quantity": 1,
            "name": "Name",
            "discount": 0.14
        }
    },
    "payment_type": "Credit Card",
    "payment_provider": "Visa",
    "paid_status": true,
    "total": 22
    }
}

The items field is a text field in the database and I am using serialize to convert it to hash:

serialize :receiptitems, Hash

My strong params are defined in this way:

params.require(:receipt).permit(:payment_type, :payment_provider, :paid_status, :total, items: params[:receipt][:items].try(:keys))

Since the items are dynamically generated I now receive an error:

Unpermitted parameters: item1, item2, item3

How can I fix this? I tried tap method and it did not work as well.

Upvotes: 0

Views: 186

Answers (1)

ruby_newbie
ruby_newbie

Reputation: 3285

You need to add the line

accepts_nested_attributes_for  :price, :quality, :name, :discount

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Upvotes: 1

Related Questions