25 User Associations - getfretless/bluit GitHub Wiki

SOLUTION:

Add a user_id foreign key column to posts.

$ bin/rails g migration AddUserRefToPosts user:references

add_user_ref_to_posts.rb

class AddUserRefToPosts < ActiveRecord::Migration
  def change
    add_reference :posts, :user, index: true, foreign_key: true
  end
end

The generator automatically adds a foreign key constraint as well, enforcing referential integrity at the database level.

Migrate the database.

$ bin/rake db:migrate

Add a belongs_to association on the Post model, and include user in the default scope.

app/models/post.rb

  belongs_to :user
  default_scope { order('updated_at DESC').includes(:category).includes(:user) }

Add a has_many association on the User model.

app/models/user.rb

  has_many :posts

When posts are created, associate them with current_user.

app/controllers/posts_controller.rb

  def create
    post = Post.new post_params
    post.user_id = current_user.id

Display the username on each post.

_app/views/posts/slug.html.erb

<div class="title"><a href="<%= post_url(post) %>"><%= post.title %></a></div>
<div class="tagline" title="<%= post.created_at %>">
  submitted <%= time_ago_in_words post.created_at %> ago
  to <%= link_to post.category.name, category_path(post.category) %>
  <%= "by #{post.user.username}" if post.user.present? %>
</div>

Got all that? Let's commit.

$ git add .
$ git commit -m "Associate users with posts."
⚠️ **GitHub.com Fallback** ⚠️