Vasseurth
Vasseurth

Reputation: 6486

How to setup an association between users and posts?

I have has_many :posts, :dependent => :destroy in my user.rb and belongs_to :user in my post.rb, in my post migration i have t.references :user and add_index :posts, :user_id and then in my routes.rb i have:

resources :users do
    resources :posts
end

How do I make it so that when i'm logged in as a user and I make a post the i can user user.posts and access those posts?

Upvotes: 1

Views: 86

Answers (2)

fl00r
fl00r

Reputation: 83680

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

Upvotes: 1

iwasrobbed
iwasrobbed

Reputation: 46703

An alternative is to do:

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

The bottom line is, you want the post to have a foreign key called user_id that ties it to a user object. By doing current_user.posts... it automatically associates the two.

Upvotes: 0

Related Questions