Skip to content

Use model association

Richard Huang edited this page Dec 4, 2010 · 6 revisions

Please go to http://rails-bestpractices.com/posts/2-use-model-association

Before:


class PostsController < ApplicationController

  def create
    @post = Post.new(params[:post])
    @post.user_id = current_user.id
    @post.save
  end

end

After:


class PostsController < ApplicationController

  def create
    @post = current_user.posts.build(params[:post])
    @post.save
  end

end

class User < ActiveRecord::Base
  has_many :posts
end