ruby on rails - Why i'm getting ActiveRecord::UnknownAttributeError -
i have array of objects i'm sending controller
through ajax
.
my ajax request this:
$.ajax({ data: { product: [{'name': 'ahmad', 'price': 'tench', 'quantity': '12'}, {'name': 'gulshan', 'price': 'tench', 'quantity': '12'}] }, url: '', type: "post", datatype: "json", success: function ( data ) { console.log(data); // this.setstate({ comments: data }); }.bind(this) });
controller:
def create @product = product.new(product_params) if @product.save render json: @product else render json: @product.errors, status: :unprocessable_entity end end private def product_params params.fetch(:product).permit! end
but if use create
method i'm getting same error.
i'm attaching screenshot of parameters in rails log.
i dont understand why i'm getting error?
please help.
the issue have since you're passing array of products
, rails' strong params unable determine attributes pass.
strong params expects:
params: { product: { "name" => "test" } }
this way, when require(:product).permit(:name)
, strong params module slice hash required. because hash looks following, hitting problem:
params: { product: [ {"name" => "test"}, {"name" => "test2"} ] }
--
might worth looking @ nested values:
params.permit(:product => [{:name, :price, :quantity}])
Comments
Post a Comment