2013-06-21 40 views
0

我一直在這裏過去一天左右在我的Rails 3.2.11應用程序在Ruby 1.9.3,閱讀每SO貼子接近這一點,我可以。下面看起來更接近寫這個記錄,因爲我已經很好地調整了這個行爲,因爲這個SO響應。我有一種商品,我想寫一個與商品相關的價格記錄。要學習如何創建一個基本的API,我寫了一個命名空間和一個單獨的價格控制器。Rails POST JSON不能批量分配受保護的屬性

在嘗試使用我在控制器中爲html使用的構建操作之後,我放棄了這種方法,只是在JSON調用中添加了commodity_id,因爲我期望用戶在url中包含commodity_id。我更新的Api :: PriceController#create只是Price模型的基本創建。

Commodity.rb

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

price.rb

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

prices_controller.rb

class PricesController < ApplicationController 
    def create 
    @commodity = Commodity.find(params[:commodity_id]) 
    @price = @commodity.prices.build(params[:price]) 
end 

API/prices_controller.rb

module Api 
class PricesController < ApplicationController 
    respond_to :json 
    def create 
     respond_with Price.create(params[:price]) 
    end 
    end 
    end 

的routes.rb

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

這裏是我的電話捲曲:

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

對此的反應是 「不能大規模指派保護屬性:prices_attributes」

OK,我相信我應該可以做到這一點,因爲另一個SO職位說,只要我不包括created_by,updated_by時間戳,我應該很好。但我不是。在另一個SO中發佈了一個類似的海報給我,讓他的工作使得JSON調用像AREL調用一樣,並將其包裝在一個prices_attributes中。洋金這個包裝,使它看起來像這樣:

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

返回一個「未定義的方法`price_url爲Api :: PricesController」。爲什麼這似乎不起作用?

回答

0

價格沒有嵌套價格,商品有Price模型中沒有accepts_nested_attributes_for :prices。 JSON不好,因爲你試圖在價格模型中節省嵌套屬性的價格。在第一個示例中,您的JSON應如下所示:

... "{\"commodity\":{\"prices_attributes\":[{\"price\":8,\"buyer\":\"Sam\",\"quality\":\"Bad\",\"commodity_id\":1}]} 

在JSON中通知「商品」而不是「價格」。第二個JSON是完全錯誤的。

通過閱讀API DocsRailsCast可以更好地理解Rails中的嵌套屬性。

+0

這是投HTTP修訂後的軌道:// railscasts。com/episodes/196-nested-model-form-revised – omarshammas

+0

感謝您的更新鏈接。 – sam452

+0

這讓我接近下一步。出於某種原因,它不喜歡任何形式的「8」,因爲它沒有通過價格驗證。但我會明白的。感謝你們兩位。 – sam452

0

嵌套屬性允許您爲表單內的其他模型附加表單。所以在你的情況下,你試圖在商品形式中嵌套價格形式。如果這是您的本意,那麼在你的商品類,你需要附加:prices_attributesattr_accessible

class Commodity < ActiveRecord::Base 
    attr_accessible :description, :name, :prices_attributes 
    has_many :prices 
    accepts_nested_attributes_for :prices 
end 
相關問題