2014-05-19 22 views
1

我的控制器動作應該respond_with新創建User::SmtpConfig記錄,它的模型嵌入用戶記錄裏面,但它misidentifies user_id新記錄,並提出了一個UrlGenerationErrorMongoid:respond_with新創建的嵌入對象提出UrlGenerationError

錯誤

的ActionController :: UrlGenerationError在/users/531604866465623cca000000/smtp_configs.json

沒有路由匹配{:行動=> 「節目」,:控制器=>「用戶/ smtp_configs 「, :user_id =>#< User :: SmtpConfig _id:537a84af6465620a1f090000,uname: 」f「,pwd:」a「,host:」fdsaf「,addr:」foo.bar.com「,port:nil, tls: nil,auth:nil>,:format => nil,:id => nil}缺少必需的鍵:[:id]

控制器動作

respond_to :json 

# This action is reached with the following URL path: 
# /users/:user_id/smtp_configs/:id.json 
def create 
    user = User.find(params[:user_id]) 
    @smtp = user.smtp_configs.create params 
    @smtp.id  # => BSON::ObjectId('537a85286465620a1f0a0000') 
    @smtp.user_id # => BSON::ObjectId('531604866465623cca000000') 
    respond_with @smtp 
end 

爲什麼控制器試圖在所有匹配任何路線?爲什麼user_id評估新創建的對象本身?

+0

這個問題(試圖找到show方法創建後)方法時創建不起作用常發生正確。在你的情況下,它似乎工作得很好,但。嘗試'渲染json:@ smtp'。你也使用'params',但是在rails 4中,它不應該是因爲強參數(不確定)。 – zishe

+1

'render json:@ smtp'確實能夠工作,但它不太理想,因爲它不包含驗證錯誤。 – JellicleCat

回答

1

最後,我的解決辦法是在我respond_with電話提供URL作爲location選項:

def create 
    @user = User.find(params[:user_id]) 
    @smtp = @user.smtp_configs.create(resource_params) 
    respond_with @smtp, location:polymorphic_url(@smtp, {user_id:@user, id:@smtp.id, format: :json}) 
end