Rails:嵌套资源问题

时间:2012-12-10 12:30:21

标签: ruby-on-rails ruby ruby-on-rails-3 routes nested-resources

这些是我的路线:

  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 %>

问题是模型:topic_id中的字段Post保持为空。 不应该自动获得主题的ID?

感谢

1 个答案:

答案 0 :(得分:1)

topic_id不在PostsController的create action中的params [:post]内。 因此,您需要将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
...