簡體   English   中英

JSON,respond_with和嵌套資源路由錯誤?

[英]JSON, respond_with, and nested resources routing error?

嘿大家,先謝謝你查看我的問題。

我有這樣的嵌套路線:

resources :users do
  resources :avatars
end

在創建用戶時,我還創建了一個像這樣的頭像:

def create
  @user = User.create(params[:user])
  @avatar = Avatar.create(:user_id => @user)
  # Send both User and Avatar object back
  respond_with(@user,@avatar)
end

但是,在發出一個服務器請求會產生一個不合適的User對象(應該導致JSON響應{error_key => ...})時,rails會給我以下錯誤:

ActionController::RoutingError (No route matches {:user_id=>#<User id: nil, name: nil, phone_number: "mcdkls", email: "fdsa@cmadksl", password_hash: nil, password_salt: nil, auth_token: nil, admin: false>, :action=>"show", :controller=>"avatars", :id=>#<Avatar id: 19, user_id: 1, created_at: "2011-05-20 01:52:22", updated_at: "2011-05-20 01:52:22">}):
app/controllers/users_controller.rb:13:in `create'

看起來像Rails試圖顯示HTML而不是JSON,但如果我像這樣改變我的控制器:

def create
  @user = User.create(params[:user])
  @avatar = Avatar.create(:user_id => @user)
  # Send both User and Avatar object back
  respond_with(@user)
end

Rails為我返回一個漂亮的{name =>“不能為空”}。 有什么想法嗎?

萬分感謝Jared

實際上沒有對此進行過測試,但問題可能是您調用'respond_with'時出現的多個對象? 相反,嘗試將對象放入數組:

def create
  @user = User.create(params[:user])
  @avatar = Avatar.create(:user_id => @user)
  # Send both User and Avatar object back
  respond_with([@user,@avatar])
end

請參閱reply_with代碼的撰稿人,Jose Valim的最后評論:

http://archives.ryandaigle.com/articles/2009/8/6/what-s-new-in-edge-rails-cleaner-restful-controllers-w-respond_with

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM