2014-05-08 34 views
2

我有一個Rails的API和我有兩個型號:如何從API請求創建嵌套模型?

class Event < ActiveRecord::Base 

    belongs_to :category 

    has_many :event_categories 
    has_many :events, through: :event_categories 

    attr_accessible :title, :description, :event_categories_attributes 

    accepts_nested_attributes_for :event_categories 

end 

class EventCategory < ActiveRecord::Base 

    belongs_to :event 
    belongs_to :category 

    attr_accessible :category_id, :event_id, :principal 

    validates :event, :presence => true 
    validates :category, :presence => true 

    validates_uniqueness_of :event_id, :scope => :category_id 

end 

在第一關鍵時刻,EventCategory是不存在的,所以我創建活動的資源上發送PARAMS像event[title]='event1', event[description] = 'blablbla'思想POST REST請求。

我的API EventsController是這樣的(我沒有一個新的方法,因爲我不需要意見):

def create 
    @event = Event.create(params[:event]) 
    if @event 
     respond_with @event 
    else 
     respond_with nil, location: nil, status: 404 
    end 
    end 

這樣正確地爲我工作。現在,使用新的EventCategory模型,我不知道如何在同一時間創建EventCategories模型。

我想這...但它不工作:

def create 
    @event = Event.new(params[:event]) 
    @event.event_categories.build 
    if @event.save 
     respond_with @event 
    else 
     respond_with nil, location: nil, status: 404 
    end 
    end 

Rails的告訴我說:

{ 
    "event_categories.event": [ 
     "can't be blank" 
    ], 
    "event_categories.category": [ 
     "can't be blank" 
    ] 
} 

我送category_id這樣的:

event[event_categories_attributes][0][category_id] = 2 

有什麼建議嗎?

+0

,你能告訴我們你的PARAMS哈希? – user3334690

+0

(rdb:1)p params {「event」=> {「title」=>「blabalb」,「description」=>「mas baksldbadbnlas」,「event_categories_attributes」=> {「0」=> {「category_id」 =>「1」}}},「access_token」=>「24cd498338b8f305dc925d9fba319ad05f258f1ec0869d676bb35fea9930ce8c」,「format」=>「json」,「a ction」=>「create」,「controller」=>「api/v1/events」 } (rdb:1) – user1364684

回答

0

在你create行動,而不是這樣的:

@event.event_categories.build 

試試這個:

@event.event_categories = EventCategory.new do |ec| 
    ec.event = @event 
    ec.category = the_cattegory_you_want_to_specify 
    # You need both of these as you are validating the presence of event AND category 
end