2013-06-24 43 views
1

我不確定爲什麼下面的cURL調用似乎不會將我期望通過json得到的值傳遞給Ruby 1.9.3中的Rails 3.2.11應用程序。我有一個帶有accepted_nested_attributes價格的商品模型,但使用了我在SO上發現的幾個cURL調用,除了應該是線索的commodity_id之外,每個屬性都會出現NULL。但對我來說並不明顯。當然,價格模型有一個用於commodity_id的字段,您可以通過我的電話看到發行人必須知道價格是針對commodity_id = 1的。下面的兩個調用都會產生相同的結果。這可能只是一個錯位的逗號或別的東西,但沒有看到它。Rails json POST傳遞NULL值

commodity.rb

class Commodity < ActiveRecord::Base 
    attr_accessible :description, :name 
    has_many :prices 
    accepts_nested_attributes_for :prices 
end 

prices.rb

class Price < ActiveRecord::Base 
    attr_accessible :buyer, :date, :price, :quality, :commodity_id 
    belongs_to :commodity 
end 

API/prices_controller.rb

module Api 
class PricesController < ApplicationController 
    respond_to :json 

     def create 
     commodity = Commodity.find(params[:commodity_id]) 
     respond_with :api, :commodity, commodity.prices.build(params[:price]) 
    end 
end 

的routes.rb

namespace :api, defaults: {format: 'json'} do 
    resources :commodities, only: [:show, :new, :create] do 
    resources :prices 
    end 
end 

這裏有兩個捲曲呼籲:基於SO尋找空應答

curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST http://localhost:3004/api/commodities/1/prices -d "{\"commodity\":{\"prices_attributes\":[{\"price\":\'8\',\"buyer\":\"Sam\",\"quality\":\"Bad\",\"commodity_id\":1}]}}"\",\"commodity_id\":1}]}}" 

第二:

curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST http://localhost:3004/api/commodities/1/prices -d "price[price]=6" -d "price[buyer]=Sam" -d "price[quality]=good" -d "price[commodity_id]=1" 

他們倆產量:

{"buyer":null,"commodity_id":1,"created_at":null,"date":null,"id":null,"price":null,"quality":null,"updated_at":null}* 

什麼我沒有看到? thanx,山姆

回答

0

我認爲總體上你試圖錯誤地使用嵌套屬性。當您正確使用它時,只會將其張貼到您的商品管理員。在這種情況下,您可以使用您在prices_attributes中傳遞的價格進行更新。

要獲得工作,你將需要添加:prices_attributes您attr_accessible方法您的商品法的

你的例子不是存儲屬性,因爲PARAMS [:價格]沒有你所期望的數據。 params [:commodity] [:prices_attributes] [0]具有正確的數據。乙

,如果你有API的發佈和更新或創建一個單一的價格你應該改變你的捲曲使用PARAMS [:價格]並在短短價格哈希

一般發送數據,檢查鐵軌控制檯後,看看什麼樣的參數,並確保他們是你所期望的。