2011-08-02 10 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=): 
回目の試行のための

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. 

任意の提案210

は、私はまた、(第二試しを)試してみましたか?

messagecommentTopicモデルにおける関連として定義されている場合のおかげ

答えて

0

、あなたがそれらに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で隠しフィールドを含める必要があります。しかし、コメントに関しては、それはまだ存在しないかのように私に見えるので、明らかにIDはありません。この場合、作成しているトピックに対してcreate_commentを使用する必要があります。 –

関連する問題