Reputation: 2453
I'm having problems changing the data type of a particular model's attribute (i.e. money). Money was an integer -- I'm trying to use a migration to change it to a decimal, with a precision of 5 and a scale of 2. Upon doing the migration, everything looks OK in console (i.e. it appears the migration worked), but when I go to change a value to a decimal in the web app, I get an 'Invalid value' message. The error appears to be taking place on the client-side for some reason (it's a js popup)? I didn't include any client-side validations though. Here are the steps I take:
First, I generate the migration:
>rails generate migration change_data_type_for_user_money
Then, I edit the migration. Here's what it looks like:
class ChangeDataTypeForUserMoney < ActiveRecord::Migration
def self.up
change_table :users do |t|
t.change :money, :decimal, :precision => 5, :scale => 2
end
end
def self.down
change_table :users do |t|
t.change :money, :decimal, :precision => 5, :scale => 2
end
end
end
Then I do a 'rake db:migrate'
What is odd is that zero's following the decimal point appear and are fine (e.g. 100.00 is OK, but 100.50 is when I get the error)
Also, here's the model:
class User < ActiveRecord::Base
attr_accessible :money, :name
validates :money, :name, :presence => true
validates :money, :numericality => true
end
And the _from view:
<%= form_for(@user) do |f| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :money %><br />
$<%= f.number_field :money %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Any thoughts? Thanks in advance for your help!
Upvotes: 1
Views: 3933
Reputation: 10394
Not sure, but try:
class ChangeDataTypeForUserMoney < ActiveRecord::Migration
def change
change_table :users do |t|
t.decimal :money, :precision => 5, :scale => 2
end
end
end
EDIT: Turned out the issue was not with migration at all, but the validator. The solution was to change: <%= f.number_field :money %> to <%= f.text_field :money %> as per my comment below.
Upvotes: 3