2011-05-24 33 views
0

如何在父模型之外創建關聯的模型實例?用於創建嵌套資源實例的表格

我有一個嵌套的資源

# config/routes.rb 
resources :users do 
    resources :messages 
end 

# models/user.rb 
has_many :messages 
# some other user model specifications 

# models/messages.rb 
belongs_to :user 

我跟着RailsTutorial.org推出的認證程序;所以我有一個助手稱爲current_user它返回一個登錄的用戶,該方法是在包含在ApplicationController

# views/messages/new 
= form_for current_user.messages.build do |f| 

一個SessionsHelper模塊此線在視圖中吐出的錯誤

undefined method 'messages_path' for #<#<Class:0xHex_Number>:0xHex_Number 

這個想法是讓用戶在他們自己之間發送消息。

回答

0

我通過在視圖中構建佔位符消息來解決視圖圖層錯誤。

= form_for current_user.messages.build, :url new_user_message_path(:user_id => current_user do |f| 

這使得要呈現一種形式,但是當我提交表單,瀏覽器發送一個POST請求new行動。控制檯日誌讀取...

Started POST "https://stackoverflow.com/users/1/messages/new" for 127.0.0.1 at ... 

ActionController::RoutingError (No route matches "https://stackoverflow.com/users/1/messages/new"): 

......這顯然是錯誤的。根據REST理論,接收穫取請求的函數不應響應POST請求,即函數應爲請求特定的

爲了解決這個問題,我改變了以下內容:

# controllers/messages 
    def new 
++ @message = Message.new 
    end 

# views/messages/new 
-- form_for current_user.messages.build, :url new_user_message_path(:user_id => current_user do |f| 
++ form_for [current_user, @message] do |f| 

這樣一來,在提交,在創建函數接收POST請求。在控制檯中...

Started POST "https://stackoverflow.com/users/1/messages" for 127.0.0.1 at ... 
    Processing by MessagesController#create as HTML 
    Parameters: {"authenticity_token"=>"areallylongstringthatnobodycanguess", "utf8"=>"✓", "message"=>{"title"=>"This is a breakthrough", "recipient"=>"Jamie", "content"=>"can you believe the developers got the messaging system working???"}, "user_id"=>"1"} 
Completed in 5ms 

......如預期的那樣。