2011-08-02 132 views
0

我想建立一個嵌套的模型,但我有一個問題:嵌套模型創建

在新的方法中TopicController.rb

def new 
    @topic = Topic.new 
    @topic.message = Message.find(params[:id]) 
    @topic.build_comment 
end 

現在在創造我有(第一次):

def create 
    @cuser = current_facebook_user.fetch 
    @topic = Topic.new(:topic) 

    respond_to do |format| 
    if @topic.save 
     format.html { redirect_to(@topic, :notice => 'Topic was successfully created.') } 
    else 
     format.html { render :action => "new" } 
    end 
    end 
end 

誤差第一次嘗試:

ActiveRecord::RecordNotFound (Couldn't find Message with ID=1 for Topic with ID=): 

我也嘗試(第2試):

def create 
    @cuser = current_facebook_user.fetch 
    @topic = Topic.new 
    @topic.message = params['topic']['message_id'] #enters nil instead of the message_id 
    @topic.comment = params['topic']['comment_id'] #enters nil instead of the comment_id 
    @topic.user = User.find(1) #enters correct user_id 

    respond_to do |format| 
    if @topic.save 
     format.html { redirect_to(@topic, :notice => 'Topic was successfully created.') } 
    else 
     format.html { render :action => "new" } 
    end 
    end 
end 

誤差第二次嘗試:

No Error but Topic.message_id = nill and Topic.comment_id = nill. Those values are not assigned. 

有什麼建議?

感謝

回答

0

如果messagecomment被定義爲Topic模型關聯,你不應該分配ID給他們,但對象,像這樣:

@topic.message = Message.find(params[:topic][:message_id]) 
@topic.comment = Comment.find(params[:topic][:comment_id]) 

時纔有意義的當然,如果messagecomment都已經被創建。

+0

它說無法找到沒有ID的消息。我的表單中是否應該有一個帶ID的隱藏字段? – Immo

+0

如果它不是這種形式,它不會被轉移,因此也不在參數中。如果消息和註釋都是主題存在之前存在的對象,那麼您的代碼纔有意義。否則,ID尚不存在,您需要在創建操作中構建關聯的對象。 –

+0

所以,是的,例如你需要在表單中包含一個帶有message_id的隱藏字段。但關於評論,它看起來好像它還不存在,很顯然沒有身份證。在這種情況下,您必須對您正在創建的主題使用create_comment。 –