Rails 4 Strong Params has_many with JSON

后端 未结 1 1078
轮回少年
轮回少年 2021-02-11 07:50

I\'m attempting to pass json up on the client side and have rails take care of handling the object creation.

Here are my models:

class Order < ActiveR         


        
相关标签:
1条回答
  • 2021-02-11 08:51

    The workaround is not necessary in this case. ActiveRecord provides an automagic way of creating child elements directly through the params hash. In order to accomplish this, follow the steps bellow:

    1. Configure Nested Attributes in the model

      class Order < ActiveRecord::Base
        # autosave is already enabled with accepts_nested_attributes_for
        has_many :order_items
        belongs_to :menu_session
      
        accepts_nested_attributes_for :order_items
      end
      
    2. Include a *_attributes key in your JSON. In your case, change the order_items key to order_items_attributes

      {'order': {'comments': 'none', 'menu_session_id': '9', 'order_items_attributes':[{'menu_item_id': '5'}, {'menu_item_id': '5'}]}};
      
    3. In your controller, make permit accept your new key

      def order_params
        params.require(:order).permit(:comments, :menu_session_id, :order_items_attributes => [:menu_item_id])   
      end
      

    There is some more awesomeness possible to accomplish with Nested Attributes. For further information, see ActiveRecord::NestedAttributes at Rails API

    0 讨论(0)
提交回复
热议问题