Field 'class' doesn't have a default value - mysql

In our app, I have a class describing a person (eye and hair colour, height, etc). Once the form of registering is fulfilled, I click in the submit button, and an exception is thrown:
Class: java.sql.SQLException
Message: Field 'class' doesn't have a default value
I am scratching my head about this, because none of the classes have a field named class, for obvious reasons (it's a reserved word), and in the database there is no column named class, neither.
Any idea why this happens? And how to fix it?
EDIT:
I tried this:
classThrowingExceptionInstance.class=ClassThrowingException
And now it says Cannot set readonly property: class for class ClassThrowingException

It seems that it is MySQL error 1364 - Message: Field '%s' doesn't have a default value.
Check the table which you modify. Are there any fields without default values? Also analyze INSERT and UPDATE statements if they do not post these field values.
To fix this error:
modify table - set DEFAULT values for fields you need
or
pass concrete values to these fields in INSERT/UPDATE statements.

Related

MySQL ERROR 1265: Data truncated for column

I can't figure out why I'm getting this message. I'm using MySQL Workbench and am editing the values in an ENUM field that connects to a dropdown choice in my app.
Everything seems to be fine. I've searched on this error and all I find refers to datatype mismatches but, in this instance, that's not possible with ENUM when feeding it an array of string values.
Here's the SQL
Executing:
ALTER TABLE `mydbase`.`average_monthly_expenses`
CHANGE COLUMN `expense_category` `expense_category` ENUM('Home', 'Healthcare', 'Child care', 'Groceries and supplies', 'Eating out', 'Utilities', 'Telecomms', 'Laundry and cleaning', 'Clothes', 'Education', 'Entertainment gifts vacation', 'Auto and transportation', 'Insurance', 'Savings and investments', 'Charitable contributions', 'Itemized monthly payments') NULL DEFAULT NULL ;
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1265: Data truncated for column 'expense_category' at row 1
SQL Statement:
ALTER TABLE `mydbase`.`average_monthly_expenses`
CHANGE COLUMN `expense_category` `expense_category` ENUM('Home', 'Healthcare', 'Child care', 'Groceries and supplies', 'Eating out', 'Utilities', 'Telecomms', 'Laundry and cleaning', 'Clothes', 'Education', 'Entertainment gifts vacation', 'Auto and transportation', 'Insurance', 'Savings and investments', 'Charitable contributions', 'Itemized monthly payments') NULL DEFAULT NULL
Any suggestions are very welcome
The query itself is correct.
modelling fiddle
Execute
SELECT DISTINCT expense_category, HEX(expense_category)
FROM mydbase.average_monthly_expenses
and check the output for the values which are not listed in the column definition.
There may be typos, leading/trailing spaces or another non-printed symbols, double spaces in the middle of the value, or there may be some collation problems.
UPDATE
My current field definition I'm trying to change to the above is ENUM('Home', 'Living', 'Telecommunications', 'Transportation', 'Other'). When I run your suggested SQL I just get Housing and Other listed.
These values are absent in new column definition - so server cannot convert them and truncates the values.
Recommendations: alter column definition, add new values to ENUM values list but do not remove old ones; update table and replace old values with new ones; alter column definition and remove old values from the list.
#Akina
So I figured out why I was blocked from editing the values. It would not let me make any edits that changed either value "Housing" or "Other". I did as you suggested, adding my new values to the existing ones, no problem, that worked fine. I couldn't however delete "Housing" or "Other", but the other prior values deleted fine. For the moment, I kept both, using "Housing" instead of "Home" and leaving "Other" at the end.
But I wanted to know however why those two values were protected, and then it dawned on me, there were existing records using those values. I manually changed all instances using "Other" to "Telecomms" and then I could remove "Other" from the ENUM values. All good now.

issue with column name 'type' in rails 3

I have a columns named 'type' in one of my tables. When I try to access it like group.type, I got the following error:
super: no superclass method `type' for #<Group:0x000000035eaf30>
However, when I try to rename the column using a migration, I get the following error
No such column: groups.type (migration failed)
I tried to rename the column directly in the mysql db, using a query, but that doesn't work either.
mysql> alter table groups change type group_type int(11);
ERROR 1054 (42S22): Unknown column 'type' in 'groups'
Please help.
The error comes from the single table inheritance feature that comes with ActiveRecord. Just tell it to use a different column than type:
class Group < ActiveRecord::Base
self.inheritance_column = nil
#...
end
With that, you don't have to rename the column.
I think type is ReservedWords in Ruby on Rails.
So try to access like this:
groups.[type]
I think you'll find you have to surround the word type with a backtick (`). 'type' is a reserved word I think and that's what will be causing your error.
I'm on my phone right now so I can't paste the character you need but it's in the top left of most standard keyboards.

Problem with fieldname having '?'

I have a 'user' table with a field name 'process_salary?' which has a boolean datatype
#user = User.create(params[:user])
if #user.process_salary?
//some code here
else
//some code here
end
When I create a new object of user and check for process_salary it gives me following error
NoMethodError: undefined method `process_salary?' for #<User:0xb6ac2f68>
Why does this error occur? Can I avoid it without changing my column name?
When I check it with the debugger it crashes the first time, but after that it runs properly
The question-mark has a special meaning in ActiveRecord. It can be used to check whether a field is true. You are using it as part of your field name which wasn't such a good idea. You could try if #user.process_salary?? exists but I think ultimately it is easiest to change your database column to be called 'process_salary'.
Side note: The 'rails console' is really helpful for playing around with models.
As cellcortex posted, question marks at the end of column names are tricky in Rails. If you need to have it there for legacy reasons, you might be able access the attribute as follows:
#user['process_salary?']
or the more verbose:
#user.read_attribute['process_salary?']
You can of course test for nil using .nil?.

Problem with MYSQL (INSERT)

i have model question with text and token fields. Want to add data into this via scaffold.
This is my question_ controller
def create
# #question = Question.new(params[:question])
#question = Question.create(:text => params[:text], :security_token => Digest::SHA1.hexdigest(rand(1000000).to_s))
render :json => #question.to_ext_json(:success => #question.save)
end
When i press "ADD" button i get in console this:
Question Create (0.0ms) Mysql::Error: Column 'text' cannot be null: INSERT INTO `questions` (`created_at`, `updated_at`, `text`, `security_token`) VALUES('2011-04-05 09:07:37', '2011-04-05 09:07:37', NULL, 'bf44551f11ce202b88d521a1826ab6db4254ce55')
Why COlumn 'text' can't be null?
You created the text column for the questions table with a NOT NULL constraint, and params[:text] is probably nil.
Since you used the scaffolding form params[:question][:text] returns the contents for text, not params[:text]!
Because the column in the database table is defined as 'not null'?
You are passing an empty text value (NULL/nil) to a database field which has NOT NULL constraint defined. You need to either ensure, that text is never empty or release this constraint, allowing NULLable fiels in the MySQL database.
I would suggest that you add a validation in your model to verify if text is null. as such, you will be spared from this low level error.
This error is nothing to do with ruby or rails, its just because you have defined the column as not null (.. as everybody says... :D ) , You might want to check your migration to see if you defined the column as not null there..
cheers
sameera

linq to sql string property from non-null column with default

I have a LINQ to SQL class "VoucherRecord" based on a simple table. One property "Note" is a string that represents an nvarchar(255) column, which is non-nullable and has a default value of empty string ('').
If I instantiate a VoucherRecord the initial value of the Note property is null. If I add it using a DataContext's InsertOnSubmit method, I get a SQL error message:
Cannot insert the value NULL into column 'Note', table 'foo.bar.tblVoucher'; column does not allow nulls. INSERT fails.
Why isn't the database default kicking in? What sort of query could bypass the default anyway? How do I view the generated sql for this action?
Thanks for your help!
If you omit the column, the value becomes the database default, but anything you insert is used instead of the default, example:
INSERT INTO MyTable (ID, VoucherRecord) Values(34, NULL) -- Null is used
INSERT INTO MyTable (ID) Values(34) -- Default is used
Picture for example you have a column that defaults to anything but NULL, but you specifically want NULL...for that to ever work, whatever value you specify MUST override the default, even in the case of NULL.
You need to set Auto-Sync to OnInsert, Auto Generated Value to true and Nullable to false for your column to work. See here for a full run-down with explanation on the Linq side.
For viewing the generated SQL, I have to recommend LinqPad