Last active
January 27, 2017 20:27
-
-
Save pilaf/bfc70eeea3e883bc1b1165e7042199dd to your computer and use it in GitHub Desktop.
Favorite candy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#== 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% @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