2012-12-10 67 views
0

這些都是我的路線:的Rails:嵌套資源問題

resources :forums, :shallow=>true do 
    resources :topics, :shallow=>true do 
     resources :posts 
    end 
    end 

topics/show.html.erb我添加了一個形式來告別後(Post就像是一個Topic評論)

<%= form_for [@topic, @post] do |f| %> 
    <div class="field"> 
    <%= f.label "content" %><br /> 
    <%= f.text_area :content %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

問題模型Post內的字段:topic_id保持空白。 不應該自動獲取主題的ID嗎?

感謝

+0

自動?不可以。顯示將表單數據保存到新模型實例的代碼。 – deefour

回答

1

的topic_id是不是裏面PARAMS [:帖]在創建PostsController的作用。 所以你需要指定topic_id手動發佈,如下所示:

... 
@post = Post.new(params[:post]) 
@post.topic_id = params[:topic_id] 
if @post.save 
    flash.notice "Post created successfully" 
else 
    flash.error "Error saving post" 
end 
... 
+0

post = Topic.find(params [:topic_id])。posts.build(params [:post])可能更有彈性。將Topic.find放在該控制器的過濾器之前也是一個好主意。 –