2011-12-30 13 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

+0

私はおそらく持っていたはずですが、レールで作業していたのは早い段階でした...今は300個の製品がありますので、分かりませんでした...それらを変えることは吸うでしょう –

+0

すべきではありません。下の私の答えを見てください。 – Amadan

答えて

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 

(未テストを実行しますおそらく調整する必要がありますまた、任意のつかまえる前にあなたのDBをバックアップ - 私はすべてのデータについては責任を負いませんあなたが苦しんでいる損失)

EDIT私は忘れてしまったことの一つ:それを印刷する方法。

<%= number_to_currency @product.price %> 

1999.99の価格のためにあなたに$1,999.99のようなものを与える必要があります。

+0

これは大変意味があります...だから私はmysqlあなたはgsubをして小数に変換しているように見えます。 –

+0

@TJSherrill:正確にそうです。 – Amadan

+0

チャームのように働いた。情報をありがとう。私はまだRails 2.3.xを実行しているので少し修正する必要がありましたが、私はそれを得て助けに感謝します –

1

String.gsubを使用すると、カンマを検索して何も置き換えることができません。

+0

これは私のために働いた。ありがとう –

+0

あなたが数字以外のすべてを取り除きたい場合は、あなたも可能です:your_value_string.scan(/ \ d /)。join( '') – miked

関連する問題