2011-05-15 37 views
12

如何关联我创建时登录到我的帖子的当前用户?设计如何将当前用户与帖子关联?

我桩模型:

before_create :owner 
belongs_to :user 
def owner 
    self.user_id = current_user.id 
end 

但是dosent工作,因为我不能在模型中使用的方法CURRENT_USER。

这里是我的控制器:

class PostsController < ApplicationController 
before_filter :authenticate_user! 

    # GET /posts 
    # GET /posts.xml 
    def index 
    @posts = Post.all 

    respond_to do |format| 
     format.html # index.html.erb 
     format.xml { render :xml => @posts } 
    end 
    end 

    # GET /posts/1 
    # GET /posts/1.xml 
    def show 
    @post = Post.find(params[:id]) 

    respond_to do |format| 
     format.html # show.html.erb 
     format.xml { render :xml => @post } 
    end 
    end 

    # GET /posts/new 
    # GET /posts/new.xml 
    def new 
    @post = Post.new 

    respond_to do |format| 
     format.html # new.html.erb 
     format.xml { render :xml => @post } 
    end 
    end 

    # GET /posts/1/edit 
    def edit 
    @post = Post.find(params[:id]) 
    end 

    # POST /posts 
    # POST /posts.xml 
    def create 
    @post = Post.new(params[:post]) 

    respond_to do |format| 
     if @post.save 
     format.html { redirect_to(@post, :notice => 'Post was successfully created.') } 
     format.xml { render :xml => @post, :status => :created, :location => @post } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @post.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

    # PUT /posts/1 
    # PUT /posts/1.xml 
    def update 
    @post = Post.find(params[:id]) 

    respond_to do |format| 
     if @post.update_attributes(params[:post]) 
     format.html { redirect_to(@post, :notice => 'Post was successfully updated.') } 
     format.xml { head :ok } 
     else 
     format.html { render :action => "edit" } 
     format.xml { render :xml => @post.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /posts/1 
    # DELETE /posts/1.xml 
    def destroy 
    @post = Post.find(params[:id]) 
    @post.destroy 

    respond_to do |format| 
     format.html { redirect_to(posts_url) } 
     format.xml { head :ok } 
    end 
    end 
end 

如何建立关联?所以,在你创建的行动,后USER_ID coloumn被分配的current_user.id

回答

29

添加

@post.user = current_user 

或者,如果你有User模式has_many :posts协会做:

@post = current_user.posts.new(params[:post]) 

if @post.save 
    ... 
+1

用户更改current_user和“破解”网站 – Max 2011-05-15 15:45:33

+3

,当你通过hidde_field在窗体中,然后可能,当在控制器 - 安全 – 2011-05-15 15:48:01

21

我建议通过您的用户创造你的信息:

# in create 
@post = current_user.posts.build(params[:post]) 

这会自动在user_id为您填写。

+0

是不是好? – LearningRoR 2011-05-27 06:24:03

+3

无论哪种方式都不错。但是你的'show','edit','update'和'destory'方法有一点。以目前的方式,用户A可以查看,更新或删除用户B的帖子。因此,通常最好使用scoped方法来检索帖子,即'show'中的'@post = current_user.posts.find(params [:id])''。当然,如果你真的想要其他用户更新对方的帖子,你的方式很好 – PeterWong 2011-05-27 06:35:55

+0

哦,好的,谢谢你的解释。我将在我的应用程序中使用此方法。 – LearningRoR 2011-05-27 13:30:28

相关问题