・ Application using rails -The Recipe model is has_many and is linked to the Like model.
recipe.rb
has_many :passive_likes, class_name: "Like",
foreign_key: "liked_id",
dependent: :destroy
like.rb
class Like < ApplicationRecord
belongs_to :liker, class_name: "User"
belongs_to :liked, class_name: "Recipe"
validates :liker_id, presence: true
validates :liked_id, presence: true
end
・ Displayed in descending order according to the number of liked_ids (count) of the Like model associated with the Recipe model. I want to sort it so that it will be done.
app/views/recipes/index.html.erb
<p><%= link_to "Recent", recipes_path(option: "recent") %></p>
<p><%= link_to "Popular", recipes_path(option: "popular")%></p>
→ Click "Recent" => "recent" is passed as an option. Click "Popular" => "pupular" is passed as an option.
app/controllers/recipes_controller.rb
def index
if params[:option] == "recent" || params[:option] == nil
@page_title = "Recent Recipes"
@recipes = Recipe.all.order(created_at: :desc).paginate(page: params[:page])
elsif params[:option] == "popular"
@page_title = "Popular Recipes"
#Recipe and Like table (has_many :passive_likes) are fused. → Like table like_id(==Recipe.id)Group with. (Even if there are multiple, combine them into one.) → Sort in descending order based on the number. → Among them, the new one comes first. →{recipe.id: liked_Number of ids}Hash is back. (Liked_Number of ids量を基準にした降順 + その中でも新しいものが先に。)
recipes_hash = Recipe.joins(:passive_likes).group("liked_id").order('count_all DESC').order(created_at: :desc).count
#recipe.Make an array of hash keys only.
recipe_ids = recipes_hash.keys
#recipe_Returns Recipe as an array in the order of ids.
recipe_array = Recipe.find(recipe_ids).sort_by{ |recipe| recipe_ids.index(recipe.id)}
#Recipe using Kaminari Gem_array(liked_Descending number of ids and created_at descending order)In the order of`@recipes`Substitute the recipe array for.
@recipes = Kaminari.paginate_array(recipe_array).page(params[:page]).per(20)
end
end
→ Array enables pagination.
default_scope-> {order (created_at :: desc)}
described in Recipe.rb.to
@ recipes` on each controller as needed.Recommended Posts