在Rails中将强参数作为JSON传递4

时间:2014-09-20 17:42:46

标签: ruby-on-rails

我想在Rails 4.1.0中为我的创建操作传递一些嵌套参数作为JSON。

我的控制器有:

def create
  debugger
  invoice = @user.invoices.new(invoice_params)

  if invoice.save
    render head: 201, location: invoice
  else
    render json: invoice.errors, status: 422
  end
end

def invoice_params
  params.require(:invoice).permit(:document_no, :customer_id, :currency_id,
      :date, :due_date, :notes, :total, :tax_total, :grand_total, :invoice_status_id,
      invoice_lines: [:product_id, :description, :quantitiy, :price])
end

如果我使用调试器检查发送的参数:

(byebug) params
{{"invoice":{"document_no":"A-500001","customer_id":1,"currency_id":1,
"date":"2014-09-20","due_date":"2014-09-20","notes":"dasdfsdf",
"total":100,"tax_total":18,"grand_total":118,"invoice_status_id":1,
"invoice_lines":"=>{"product_id":1,"quantity":1,"price":200}"=>{}}=>nil}}, 
"format"=>:json, "action"=>"create", "controller"=>"api/v1/invoices"}

请注意:我在发布此处之前清除了上面输出中的反斜杠。

我的集成测试代码:

require 'test_helper'

class CreatingInvoiceTest < ActionDispatch::IntegrationTest
  setup do
    @user = User.create!(username: 'foo@example.com', password: '123456')
  end

  test 'Creating Invoice' do

    post('/api/v1/invoices', {
      invoice: {
        document_no: 'A-500001',
        customer_id: 1,
        currency_id: 1,
        date: Time.now,
        due_date: Time.now,
        notes: 'dasdfsdf',
        total: 100,
        tax_total: 18,
        grand_total: 118,
        invoice_status_id: 1,
        invoice_lines: [{product_id: 1, quantity: 1, price: 200}]
      }
    }.to_json,
    {'Authorization'=> token_header(@user.token)})

    assert_equal 201, response.status
    assert_equal Mime::JSON, response.content_type

  end
end

我的模特有:

has_many :invoice_lines
accepts_nested_attributes_for :invoice_lines

我遇到以下错误:

CreatingInvoiceTest#test_Creating_Invoice: ActionController::ParameterMissing: param is missing or the value is empty: invoice app/controllers/api/v1/invoices_controller.rb:29:in `invoice_params' app/controllers/api/v1/invoices_controller.rb:9:in `create' test/integration/creating_invoice_test.rb:10:in `block in <class:CreatingInvoiceTest>'

我看不到我在这里缺少的东西。

0 个答案:

没有答案