Skip to content

Instantly share code, notes, and snippets.

@pilaf
Last active January 27, 2017 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pilaf/bfc70eeea3e883bc1b1165e7042199dd to your computer and use it in GitHub Desktop.
Save pilaf/bfc70eeea3e883bc1b1165e7042199dd to your computer and use it in GitHub Desktop.
Favorite candy
#== Migrations
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :name
t.timestamps
end
end
end
class CreateCandies < ActiveRecord::Migration[5.0]
def change
create_table :candies do |t|
t.string :name
t.timestamps
end
end
end
class CreateFavorites < ActiveRecord::Migration[5.0]
def change
create_table :favorites do |t|
t.references :favoritable, polymorphic: true
t.references :user
t.timestamps
end
end
end
#== Models
class User < ActiveRecord::Base
has_many :favorites
end
class Candy < ActiveRecord::Base
has_many :favorites, as: :favoritable
def favorite_by_user?(user)
favorites.where(user_id: user).exists?
end
end
class Favorite < ActiveRecord::Base
belongs_to :favoritable, polymorphic: true
belongs_to :user
end
#== Controller
class CandiesController < ApplicationController
def index
@candy = Candy.all
end
end
<% @candy.each do |candy| -%>
<%= candy.name %>
<% if candy.favorite_by_user?(current_user) -%>
<% end -%>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment