-
Notifications
You must be signed in to change notification settings - Fork 1
25 User Associations
Dave Strus edited this page May 7, 2015
·
2 revisions
Add a user_id foreign key column to posts.
$ bin/rails rails g migration add_user_id_to_postsadd_user_id_to_posts.rb
class AddUserIdToPosts < ActiveRecord::Migration
def change
add_reference :posts, :user, index: true
end
endMigrate the database.
$ bin/rails rake db:migrateAdd 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 :postsWhen 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.idDisplay 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."