Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise how to associate current user to post?

How do I associate my current user that is signed in to my post on create?

My post model:

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

But that dosent work because I cannot use the method current_user in model.

Here is my controller:

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

How do I build the association ? So, that the post user_id coloumn gets assigned the current_user.id

like image 283
Max Avatar asked May 15 '11 15:05

Max


2 Answers

Add

@post.user = current_user

in your create action.

Or if you have has_many :posts association on User model do:

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

if @post.save
  ...
like image 62
Sergey Kishenin Avatar answered Sep 29 '22 13:09

Sergey Kishenin


I would suggest creating your post through your user:

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

This would automatically fill in the user_id for you.

like image 32
PeterWong Avatar answered Sep 29 '22 11:09

PeterWong