2012-06-16 35 views
0

如何使用導軌3功能清理此問題?我有一個帖子,屬於一個組和一個用戶。該組和用戶has_many帖子。我正在使用嵌套資源Rails 3使用嵌套資源創建方法?

resources :groups do 
    resources :posts 
end 



<%= form_for @post, :url => group_posts_path(params[:group_id]) do |f| %> 
.... 
<% end %> 

def create 
    @group = Group.find(1) 
    @post = @group.posts.build(params[:post]) 
    @post.user_id = current_user.id 

    respond_to do |format| 
     if @post.save 
     ..... 
     end 
    end 
end 

謝謝。

回答

0

在模型中使用accepts_nested_attributes_for方法。

如果您不熟悉嵌套表格,請查看this railscastthe second part瞭解更多信息。

0

鑑於:

<%= form_for [@group, @group.posts.build] do |f| %> 
    ... 
    <% end %> 

在控制器:

class PostsController < ApplicationController 
    before_filter :find_group 
    ... 
    def create 
     @post = @group.posts.build(params[:post]) 
     current_user.posts << @post 
    end 

    protected 
    def find_group 
     @group = Group.find(params[:group_id]) 
    end 
    end