引き出したデータを並び替えてランキングを作りたいのですが記述の仕方がわからず困っています。
やりたいことはecサイトの売り上げランキングを作りたいと思っています。
各商品がどれだけ売れたかは引き出すことができたのですが、それを並び替えたりする方法がわかりません。
現在コントローラー内に@products = Product.allでproduct.rbに
def total_count line_items.to_a.sum { |item| item.quantity} end
でviewにeach使用してproduct.total_countで各productがどれだけ売れたかはわかるのですが、ここに.order.limitとかで実装できると思ったのですがうまくいきませんでした。何かわかりそうな方いましたらとよろしくお願いいたします!
☆追記
上記total_countはメソッドです。なのでメソッドで引き出した値を並び替えたいという事です。
以下参考データ添付させていただきます。
schema.rb
ActiveRecord::Schema.define(version: 20180508113923) do create_table "carts", force: :cascade do |t| t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "line_items", force: :cascade do |t| t.integer "product_id" t.integer "cart_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "quantity", default: 1 t.integer "order_id" end create_table "orders", force: :cascade do |t| t.string "name" t.text "address" t.string "email" t.string "pay_type" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "user_id" t.integer "product_id" t.integer "quantity" end create_table "products", force: :cascade do |t| t.string "title" t.text "description" t.string "image_url" t.decimal "price", precision: 8, scale: 2 t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "category_id" end create_table "users", force: :cascade do |t| t.string "name" t.string "password_digest" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "email" t.string "reset_digest" t.datetime "reset_sent_at" t.boolean "admin", default: false end end
line_item.rb
class LineItem < ApplicationRecord belongs_to :order belongs_to :product belongs_to :cart def total_price product.price * quantity end end
product.rb
class Product < ApplicationRecord has_many :line_items has_many :orders, through: :line_items has_many :users, through: :favorites def total_count line_items.to_a.sum { |item| item.quantity} end end
order.rb
class Order < ApplicationRecord has_many :line_items, dependent: :destroy belongs_to :user def add_line_items_from_cart(cart) cart.line_items.each do |item| item.cart_id = nil line_items << item end end def total_price line_items.to_a.sum { |item| item.total_price } end def total_count line_items.to_a.sum { |item| item.quantity} end end
以上宜しくお願いしますm(._.)m
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/12 06:49
2018/05/12 07:17
2018/05/12 09:09