mardi 23 février 2016

Implement add Recipe to favorites in Rails and find if current user has 'favorite_set?' a recipe

This question is related to that shows a has_many :through association. I have a similar association as shown in the answer. I will cite for reference.

$ rails g model FavoriteRecipe recipe_id:integer user_id:integer

# Join model connecting user and favorites
class FavoriteRecipe < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :user
end

---

class User < ActiveRecord::Base
  has_many :recipes

  # Favorite recipes of user
  has_many :favorite_recipes # just the 'relationships'
  has_many :favorites, through: :favorite_recipes, source: :recipe # the actual recipes a user favorites
end

class Recipe < ActiveRecord::Base
  belongs_to :user

  # Favorited by users
  has_many :favorite_recipes # just the 'relationships'
  has_many :favorited_by, through: :favorite_recipes, source: :user # the actual users favoriting a recipe
end

I am curious to know if this solution would work with a many-to-many relationship with joining model e.g. FavoriteRecipe that has a boolean attribute favorite_set. When iterating through the Recipes I would like to find out if the current user has 'favorited' this/these Recipes. Something like current_user.recipe.favorite_set? but of course going through the FavoriteRecipe joining model. If true display 'FAVORITE SET' otherwise give an option to favorite this recipe. My implementation is a feed that displays all "Recipes" and shows "FAVORITE SET" or gives the option to "favorite" one or multiple Recipes.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire