【发布时间】:2020-06-13 06:04:23
【问题描述】:
我有一个store with items。每件商品都有价格。
我尝试通过价格标头的价格升序和降序对它们进行排序。当我点击价格时,所有 10 美元到 50 美元之间的商品都正确排序,但低于 10 美元和高于 50 美元的商品不会与它们一起排序。
这是我的代码:
class TeethersController < ApplicationController
before_action :authenticate_user!,except: [:index,:show]
helper_method :sort_column, :sort_direction
before_action :find_teether, only: [:destroy,:edit,:update,:show]
def index
@teethers= Teether.all.order(sort_column + ' ' + sort_direction)
@colors = Array.new
@types = Array.new
@teethers.each {|t| @types << t.types.pluck(:name) }
@teethers.each {|t| @colors << t.colors.pluck(:name) }
if params[:search]
@search_term = params[:search]
@teethers= @teethers.search_by(@search_term)
end
if params[:type_id]
@types = Typation.where(type_id: params[:type_id])
@teethers = @types.map(&:teether)
end
end
def create
@teether = Teether.new(teether_attributes)
if @teether.save
redirect_to teethers_path, notice: "Thank you... Your teether information was created successfully."
else
flash.now[:error] = "Please correct the form"
render :new
end
end
def new
@teether=Teether.new
end
private
def find_teether
@teether = Teether.find(params[:id])
end
def sort_column
Teether.column_names.include?(params[:sort]) ? params[:sort] : "name"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
def teether_attributes
teether_attributes = params.require(:teether).permit([:name,:description,:price,:image,:keywords,:status,:quantity,:discount,:kind,{type_ids: []},:gender,:color,:theme])
end
end
我的应用助手是:
module ApplicationHelper
def sortable(column, title = nil)
title ||= column.titleize
direction = (column == sort_column && sort_direction == "asc")? "desc" : "asc"
link_to title, :sort => column, :direction => direction
end
end
这在我的索引中:
<h3 id="sort"><label>Sort: </label><span> | </span><span><%= sortable "price" %><span class="caret"></span></span></h3>
在数据库中
class CreateTeethers < ActiveRecord::Migration[5.2]
def change
create_table :teethers do |t|
t.string :name
t.text :description
t.string :price
t.timestamps
end
end
end
class AddDiscountToTeether < ActiveRecord::Migration[5.2]
def change
add_column :teethers, :discount, :text
add_column :teethers, :kind, :text
end
end
【问题讨论】:
-
你能显示你的牙胶表模式吗?看起来它是按字母顺序排序的,这让我觉得“价格”是一个字符串?另外(你已经注意到了,我猜)如果有的话,你真的应该按折扣价排序。
-
if params[:search]和if params[:type_id]是问题所在,当这些if为真时,order就消失了。 -
请阅读“How to Ask”及其链接页面。花点时间想一个更好的标题,因为它目前很糟糕。
-
我们需要更多信息。表的架构是什么,以及证明问题的最小价格样本。编辑您的问题并添加该信息,就好像它一直存在一样。不要使用“编辑”或“更新”类型标签,因为我们可以知道发生了什么变化。 “How to Ask”及其链接页面有助于解释。
-
@SteveTurczyn 我在我的问题中添加了数据库,是的,价格是字符串。如何解决这个问题?
标签: arrays ruby-on-rails ruby database sorting