2011-07-15 28 views
1

我有我的user.rb has_many :posts, :dependent => :destroybelongs_to :user在我post.rb,我在遷移後,我有t.references :useradd_index :posts, :user_id,然後在我的routes.rb我有:如何設置用戶和帖子之間的關聯?

resources :users do 
    resources :posts 
end 

我如何使它所以當我以用戶身份登錄併發布帖子時,我可以使用user.posts並訪問這些帖子?

回答

1
respond_to :html 

def index 
    @posts = current_user.posts 
end 

def new 
    @post = current_user.posts.new 
end 

def edit 
    @post = current_user.posts.find params[:id] 
end 

def create 
    @post = current_user.posts.new params[:post] 
    @post.save 
    respond_with @post 
end 

def update 
    @post = current_user.posts.find params[:id] 
    @post.update_attributes params[:post] 
    respond_with @post 
end 

def destroy 
    @post = current_user.posts.find params[:id] 
    @post.destroy 
    respond_with @post 
end 
0

另一種方法是要做到:

def create 
    if current_user.posts.create!(params[:post]) 
    # success 
    else 
    # validation errors 
    end 
end 

底線是,你想要的崗位有一個名爲user_id一個外鍵,它關係提高到一個用戶對象。通過做current_user.posts...它會自動關聯這兩個。

相關問題