2011-12-30 51 views
0

我有一个产品目录中的产品的价格字段。有时,管理员用户在处理数千个(例如:10,000美元)时会留下一个逗号,有时他只是在做6000美元。尽管我想简单地告诉他这样做,但我也想以编程方式解决问题。ruby​​/rails如何在订购时忽略逗号

的#show负责任的行动是在这里:

def show 
     @category = Category.find_by_url_name(params[:category_id]) 
     @brand = Brand.find(params[:id]) 

     @search = Product.find(:all, :conditions => ['brand_id = ? and category_id = ?', @brand.id, @category.id], 
      :order=> params[:order] || 'price DESC') 
     @products = @search.paginate(:page => params[:page], :per_page => 12) 

    @meta_title = "#{@brand.name}" 
    respond_to do |format| 
     format.html # show.html.erb 
     format.xml { render :xml => @brand } 
    end 
    end 

我也有我的应用助手所提供的订购选项的网站用户sort_options帮手:

def product_sort_options 
    options_for_select([ 
     ['', nil], 
     ['Newest to Oldest', 'descend_by_date'], 
     ['Oldest to Newest', 'ascend_by_date'], 
     ['Price: Highest to Lowest', 'descend_by_price'], 
     ['Price: Lowest to Highest', 'ascend_by_price'], 
     ['Name', 'ascend_by_name'] 
    ]) 
    end 

什么想法?

+3

为什么你的价格是一个字符串,首先?!?将它保留为小数点,并在显示时用''''和','装饰。在输入时剥去它们。 – Amadan 2011-12-30 17:03:01

+0

我可能应该有,但是,早在我的钢轨工作...不知道更好,现在有300个产品...所以改变他们会吸 – 2011-12-30 17:08:54

+0

它不应该。请参阅下面的答案。 – Amadan 2011-12-30 17:26:08

回答

2

要使它成为完整答案 - price不应该是一个字符串。现在你有300种产品的事实并不是什么大不了的事情。

做迁移:

rails generate migration decimalise 

然后对其进行编辑(db/migrate/*decimalise.rb),写这样的事:

class Decimalise < ActiveRecord::Migration                                              
    def up 
    connection = ActiveRecord::Base.connection() 
    # kill the weird chars in the string field 
    connection.execute("UPDATE products SET price = REPLACE(REPLACE(price, ',', ''), '$', '')") 

    # convert the string column into a decimal one 
    change_table :products do |t| 
     # adjust for your use case - this gives you values up to 9999999.99 
     # if you need more, increase the 10 
     t.column :price, :decimal, :precision => 10, :scale => 2 
    end 
    end 

    def down 
    change_table :products do |t| 
     t.column :price, :string, :limit => 10 
    end 
    end 
end 

然后最后,运行

rake db:migrate 

(未经测试,你可能需要调整,另外,在任何修补之前备份你的数据库 - 我不会对任何数据负责你受的损失)

编辑我忘了一件事:如何打印出来。

<%= number_to_currency @product.price %> 

应该给你类似$1,999.991999.99价格。

+0

哇,好吧,这样做很有意义......所以我不是mysql但是它看起来像你正在做一个gsub然后转换为十进制 – 2011-12-30 17:48:55

+0

@TJSherrill:正是如此。 – Amadan 2011-12-30 17:53:52

+0

工作就像一个魅力。谢谢(你的)信息。我不得不稍微修改一下,因为我仍然运行Rails 2.3.x,但是我明白了,并感谢帮助 – 2011-12-30 18:11:46

1

您可以使用String.gsub搜索逗号并将其替换为空白。

+0

这对我有用。谢谢 – 2011-12-30 17:28:14

+0

如果你想摆脱除数字之外的所有东西,你还可以:your_value_string.scan(/ \ d /)。join('') – miked 2011-12-30 17:36:10