QueryException in Connection.php line 662: : Integrity constraint violation: 1048 Column 'content' cannot be null - laravel-5.1

I use laravel 5.1, what can do with this error?
**strong text**in Connection.php line 662
at Connection->runQueryCallback('insert into `statuses` (`content`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46'), object(Closure)) in Connection.php line 618
at Connection->run('insert into `statuses` (`content`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46'), object(Closure)) in Connection.php line 391
at Connection->statement('insert into `statuses` (`content`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46')) in Connection.php line 347
at Connection->insert('insert into `statuses` (`content`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46')) in Processor.php line 32
at Processor->processInsertGetId(object(Builder), 'insert into `statuses` (`content`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?)', array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46'), 'id') in Builder.php line 1843
at Builder->insertGetId(array(null, '1', '2017-02-04 14:36:46', '2017-02-04 14:36:46'), 'id')
at call_user_func_array(array(object(Builder), 'insertGetId'), array(array('content' => null, 'user_id' => '1', 'updated_at' => '2017-02-04 14:36:46', 'created_at' => '2017-02-04 14:36:46'), 'id')) in Builder.php line 1015
at Builder->__call('insertGetId', array(array('content' => null, 'user_id' => '1', 'updated_at' => '2017-02-04 14:36:46', 'created_at' => '2017-02-04 14:36:46'), 'id')) in Model.php line 1592
at Model->insertAndSetId(object(Builder), array('content' => null, 'user_id' => '1', 'updated_at' => '2017-02-04 14:36:46', 'created_at' => '2017-02-04 14:36:46')) in Model.php line 1561
at Model->performInsert(object(Builder), array()) in Model.php line 1452
at Model->save() in HasOneOrMany.php line 317
at HasOneOrMany->create(array('content' => null)) in StatusesController.php line 34
at StatusesController->store(object(Request))
at call_user_func_array(array(object(StatusesController), 'store'), array(object(Request))) in Controller.php line 256
at Controller->callAction('store', array(object(Request))) in ControllerDispatcher.php line 164
at ControllerDispatcher->call(object(StatusesController), object(Route), 'store') in ControllerDispatcher.php line 112
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Authenticate.php line 45
at Authenticate->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Authenticate), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 114
at ControllerDispatcher->callWithinStack(object(StatusesController), object(Route), object(Request), 'store') in ControllerDispatcher.php line 67
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\StatusesController', 'store') in Route.php line 203
at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
at Route->run(object(Request)) in Router.php line 708
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Router.php line 710
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 673
at Router->dispatchToRoute(object(Request)) in Router.php line 635
at Router->dispatch(object(Request)) in Kernel.php line 236
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
at Kernel->handle(object(Request)) in index.php line 53
at require_once('/var/www/sample/public/index.php') in server.php line 21

Related

Rails 4 Duplicating Model Objects and Merging New Object attribtues (Amoeba Gem)

What I'm doing: Duplicating a record of my Project model then overwriting the modified attributes from an object submitted by a form. The new record should be modified but have all the associations as the original.
The first step I took was to duplicate a AR Model object, including its associations, which I'm doing with Amoeba gem.
projects_controller.rb
...
def create
if params[:copy]
orig_project = Project.find params[:copy]
#new_project = orig_project.amoeba_dup
...
Now I would like to merge my project_params into the #new_project object overwriting the attributes if the attributes are different.
projects_controller.rb
...
def create
if params[:copy]
orig_project = Project.find params[:copy]
#new_project = orig_project.amoeba_dup
my_merge_method(#new_project,project_params)
...
if #new_project.save
Could anyone provide a good way to do this with some rails magic? Thanks
Messing around in the rails console I have found that the method update_attributes for AR model objects does what I want.
For Example
new_project = orig_project.amoeba_dup
new_project.update_attributes(project_params)
...will leave the associations intact but overwrite the new_project with the project_params
Here is the rails console output to prove it.
35: def create
36: if params[:copy]
37: orig_project = Project.find params[:copy]
38: #project = orig_project.amoeba_dup
39:
=> 40: binding.pry
41: else
42: #project = Project.new(project_params)
43: end
44:
45: respond_to do |format|
46: if #project.save
47: format.html { redirect_to #project, notice: 'Project was successfully created.' }
48: format.json { render action: 'show', status: :created, location: #project }
49: else
50: format.html { render action: 'new' }
51: format.json { render json: #project.errors, status: :unprocessable_entity }
52: end
53: end
54: end
[1] pry(#<ProjectsController>)> params[:copy]
=> "201"
[2] pry(#<ProjectsController>)> #project
=> #<Project:0x00000005c38e58
id: nil,
name: "Corn Flour Milling with Setup",
scheduled_start_date: Tue, 29 Dec 2015,
estimated_end_date: Wed, 27 Jan 2016,
employees_needed: 2,
incoming_packaging: "Boxes",
final_product_packaging: "Boxes",
sample_instructions: "One 18 oz every pallet.\r\nMilled Corn Flour\r\nLot Number\r\nBag Number\r\nNet Weight",
project_description: "Mill the piss out of this.",
project_type: "Production",
building_id: "5",
paid_status: false,
material_total_weight_lbs: 40000,
shifts: 1.0,
shift_hrs: 8,
rate_lb_hr: 2000,
company_id: 1,
created_at: nil,
updated_at: nil>
[4] pry(#<ProjectsController>)> #project.setups
=> [#<Setup:0x00000005c73210 id: 22, created_at: Thu, 21 Jan 2016 14:33:09 UTC +00:00, updated_at: Thu, 21 Jan 2016 14:33:09 UTC +00:00>]
[5] pry(#<ProjectsController>)> project_params
=> {"name"=>"Corn Flour Milling with Setup",
"scheduled_start_date"=>"2016-03-25", #changed this value
"estimated_end_date"=>"2016-03-30", #changed this value
"employees_needed"=>"2",
"incoming_packaging"=>"Boxes",
"final_product_packaging"=>"Boxes",
"sample_instructions"=>"One 18 oz every pallet.\r\nMilled Corn Flour\r\nLot Number\r\nBag Number\r\nNet Weight",
"project_description"=>"Mill the piss out of this.",
"project_type"=>"Production",
"building_id"=>"5",
"paid_status"=>"false",
"material_total_weight_lbs"=>"40000",
"shifts"=>"1.0",
"shift_hrs"=>"8",
"rate_lb_hr"=>"2000",
"company_id"=>"1"}
[7] pry(#<ProjectsController>)> #project.update_attributes(project_params)
(0.6ms) BEGIN
Company Load (1.3ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1 [["id", 1]]
SQL (1.3ms) INSERT INTO "projects" ("name", "scheduled_start_date", "estimated_end_date", "employees_needed", "incoming_packaging", "final_product_packaging", "sample_instructions", "project_description", "project_type", "building_id", "paid_status", "material_total_weight_lbs", "shifts", "shift_hrs", "rate_lb_hr", "company_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) RETURNING "id" [["name", "Corn Flour Milling with Setup"], ["scheduled_start_date", "2016-03-25"], ["estimated_end_date", "2016-03-30"], ["employees_needed", 2], ["incoming_packaging", "Boxes"], ["final_product_packaging", "Boxes"], ["sample_instructions", "One 18 oz every pallet.\r\nMilled Corn Flour\r\nLot Number\r\nBag Number\r\nNet Weight"], ["project_description", "Mill the piss out of this."], ["project_type", "Production"], ["building_id", "5"], ["paid_status", "f"], ["material_total_weight_lbs", 40000], ["shifts", 1.0], ["shift_hrs", 8], ["rate_lb_hr", 2000], ["company_id", 1], ["created_at", "2016-01-21 20:07:26.508713"], ["updated_at", "2016-01-21 20:07:26.508713"]]
SQL (1.8ms) INSERT INTO "projects_setups" ("setup_id", "project_id") VALUES ($1, $2) [["setup_id", 22], ["project_id", 217]]
(32.1ms) COMMIT
=> true
[8] pry(#<ProjectsController>)>

Single call to fgetcsv() exhausting large memory limit in PHP

I am trying to read two lines from a average-sized CSV (10 MB), the header and the first line. I have the memory limit for PHP set to 64 MB. Yet, on the second call to fgetcsv(), I get a memory exhausted error.
I've removed every unessential part of the script to debug, and traced memory usage step-by-step, and I still can't figure it out. Right after the first call, memory usage is under 1 MB, but at the second call, the memory exhaust error happens.
Here's the code:
<?php
function trace($msg) {
echo "<br>" . date("Y-m-d H:i:s") . " - " . memory_get_usage() . " bytes - {$msg}";
}
ini_set('display_errors', 'on');
error_reporting(E_ALL);
ob_implicit_flush(true);
trace("CSV Memory Limit test");
$path = "../data/uploaded/1405712684_base_leitores_july2014.csv";
trace("path = {$path}");
$fp = fopen($path, "r");
trace("file pointer opened");
trace("getting header...");
$header = fgetcsv($fp, 1024);
trace("header fetched");
var_dump($header);
trace("header displayed");
trace("fetching another line");
$l1 = fgetcsv($fp, 1024);
trace("line fetched");
var_dump($header);
trace("line displayed");
Here's the output:
2014-07-18 16:06:26 - 249544 bytes - CSV Memory Limit test
2014-07-18 16:06:26 - 249800 bytes - path = ../data/uploaded/1405712684_base_leitores_july2014.csv
2014-07-18 16:06:26 - 250840 bytes - file pointer opened
2014-07-18 16:06:26 - 250840 bytes - getting header...
2014-07-18 16:06:26 - 279280 bytes - header fetched
array (size=111)
0 => string 'razao social' (length=12)
1 => string 'Identificaao' (length=13)
2 => string 'save' (length=4)
3 => string 'id' (length=2)
4 => string 'categoria' (length=9)
5 => string 'nome fantasia' (length=13)
6 => string 'email' (length=5)
7 => string 'website' (length=7)
8 => string 'logradouro' (length=10)
9 => string 'endereco' (length=8)
10 => string 'numero' (length=6)
11 => string 'complemento' (length=11)
12 => string 'bairro' (length=6)
13 => string 'cidade' (length=6)
14 => string 'estado' (length=6)
15 => string 'cep' (length=3)
16 => string 'localidade' (length=10)
17 => string 'ddd' (length=3)
18 => string 'telefone' (length=8)
19 => string 'fax' (length=3)
20 => string 'contato' (length=7)
21 => string 'cargo' (length=5)
22 => string 'departamento' (length=12)
23 => string 'ramo de atividade' (length=17)
24 => string 'data de nascimento' (length=18)
25 => string 'especialidade' (length=13)
26 => string 'linha de atuacao' (length=16)
27 => string 'data de fundacao' (length=16)
28 => string 'classificacao de leitor' (length=23)
29 => string 'observacoes' (length=11)
30 => string 'is_protocolada' (length=14)
31 => string 'is_assinante' (length=12)
32 => string 'qtd_reclamacoes' (length=15)
33 => string 'error' (length=5)
34 => string 'errorReport' (length=11)
35 => string 'saved' (length=5)
36 => string 'onTrash' (length=7)
37 => string 'SugestAo de matEria' (length=19)
38 => string 'Campo2
#redacted#' (length=31)
39 => string '1' (length=1)
40 => string '0' (length=1)
41 => string '141657' (length=6)
42 => string '2000000041' (length=10)
43 => string '' (length=0)
44 => string '' (length=0)
45 => string '' (length=0)
46 => string 'RUA' (length=3)
47 => string '#redacted#' (length=15)
48 => string '#redacted#' (length=3)
49 => string '' (length=0)
50 => string 'JABAQUARA' (length=9)
51 => string 'PARI' (length=4)
52 => string 'SP' (length=2)
53 => string '#redacted#' (length=7)
54 => string '' (length=0)
55 => string '11' (length=2)
56 => string '#redacted#' (length=9)
57 => string '#redacted#' (length=9)
58 => string '#redacted#' (length=5)
59 => string '#redacted#' (length=12)
60 => string '' (length=0)
61 => string 'Centros Automotivos, Mec‰nicas e Oficinas - Leves' (length=49)
62 => string '' (length=0)
63 => string '' (length=0)
64 => string '' (length=0)
65 => string '' (length=0)
66 => string '' (length=0)
67 => string 'Centros Automotivos, MecAnicas e Oficinas - Leves ' (length=50)
68 => string 'N' (length=1)
69 => string '0' (length=1)
70 => string '0' (length=1)
71 => string '0' (length=1)
72 => string '' (length=0)
73 => string '1' (length=1)
74 => string '0' (length=1)
75 => string '' (length=0)
76 => string '
#redacted#' (length=16)
77 => string '2' (length=1)
78 => string '0' (length=1)
79 => string '228109' (length=6)
80 => string '2000000041' (length=10)
81 => string '0800 AUTOMOTIVE' (length=15)
82 => string '#redacted##hotmail.com' (length=32)
83 => string '' (length=0)
84 => string 'RUA' (length=3)
85 => string '#redacted#' (length=7)
86 => string '322' (length=3)
87 => string '' (length=0)
88 => string '' (length=0)
89 => string 'SAO PAULO' (length=9)
90 => string 'SP' (length=2)
91 => string '#redacted#' (length=7)
92 => string '' (length=0)
93 => string '11' (length=2)
94 => string '#redacted#' (length=9)
95 => string '#redacted#' (length=9)
96 => string '#redacted#' (length=40)
97 => string 'PROPRIETARIO' (length=12)
98 => string '' (length=0)
99 => string 'Centros Automotivos, Mec‰nicas e Oficinas - Leves' (length=49)
100 => string '' (length=0)
101 => string '' (length=0)
102 => string '' (length=0)
103 => string '' (length=0)
104 => string '' (length=0)
105 => string 'Centros Automotivos, MecAnicas e Oficinas - Leves ' (length=50)
106 => string '' (length=0)
107 => string '0' (length=1)
108 => string '0' (length=1)
109 => string '0' (length=1)
110 => string 'Registro criado' (length=15)
2014-07-18 16:06:26 - 287608 bytes - header displayed
2014-07-18 16:06:26 - 287608 bytes - fetching another line
( ! ) Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 72 bytes) in /home/lqdi/quantum.pranaeditora.com.br/sandbox/test_csv_read.php on line 25
Call Stack
# Time Memory Function Location
1 0.0011 249048 {main}( ) ../test_csv_read.php:0
2 0.0093 287520 fgetcsv ( ) ../test_csv_read.php:25
I am running php5-fpm (5.5.9) and nginx (1.4.6) on Ubuntu 14.04 LTS.
Finally, after a lot of headbanging, I found the problem: line endings.
Somewhy, Mac's Excel was exporting a CSV with a \r\n on the header and \n on all other lines. The header would come in nicely, but fgetcsv understood the second line was the entire document.
The fix was to add the following before fopen:
ini_set('auto_detect_line_endings',TRUE);
This will make fgetcsv detect line endings corrently when parsing the CSV file.

Postgresql database query to Ruby active record

There are tables audits and audit_statuses, and need to fetch the data which are not common in both. I already have a query that works in postgresql , how to convert convert it into Ruby active record .
the following is the Psql query
SELECT a.name as status,count(b.audit_status_id) as count
FROM audit_statuses as a,audits as b
WHERE a.id=b.audit_status_id
GROUP BY a.name;
Your association models are Audit belongs_to Audit_status, and Audit_status has_many Audits, aren't there? And You want to get counts how many Audit_statuses owned by Audit, won't you?
If yes, you should use counter_cache read this about belongs_to Association Reference #counter_cache
Although the :counter_cache option is specified on the model that
includes the belongs_to declaration, the actual column must be added
to the associated model. In the case above, you would need to add a
column named count_audit to the Audit_status model
Add count_audit attribute to audit_statuses table by running :
rails g migration AddCountAuditToAuditStatuses count_audit:integer
and run rake db:migrate
On your models looks like :
class Audit < ActiveRecord::Base
attr_accessible :audit_status_id, :status
belongs_to :audit_status, :counter_cache => :count_audit
end
class AuditStatus < ActiveRecord::Base
attr_accessible :count_audit, :name
has_many :audits
end
Example create one record of audit_status
irb(main):001:0> audit_status = AuditStatus.create!(:name => "John Noe")
←[1m←[36m (0.0ms)←[0m ←[1mBEGIN←[0m
←[1m←[35mSQL (114.0ms)←[0m INSERT INTO "audit_statuses" ("count_audit", "created_at", "name", "up
dated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["count_audit", nil], ["created_at", Fri, 06 Jun
2014 15:17:49 WIB +07:00], ["name", "John Noe"], ["updated_at", Fri, 06 Jun 2014 15:17:49 WIB +07:0
0]]
←[1m←[36m (17.0ms)←[0m ←[1mCOMMIT←[0m
=> #<AuditStatus id: 1, name: "John Noe", count_audit: nil, created_at: "2014-06-06 08:17:49", updat
ed_at: "2014-06-06 08:17:49">
And create two records of audit, and get audit_status.id for audit_status_id
irb(main):002:0> audit = Audit.create!({:audit_status_id => audit_status.id, :status => true})
←[1m←[35m (0.0ms)←[0m BEGIN
←[1m←[36mSQL (6.0ms)←[0m ←[1mINSERT INTO "audits" ("audit_status_id", "created_at", "status", "up
dated_at") VALUES ($1, $2, $3, $4) RETURNING "id"←[0m [["audit_status_id", 1], ["created_at", Fri,
06 Jun 2014 15:19:00 WIB +07:00], ["status", true], ["updated_at", Fri, 06 Jun 2014 15:19:00 WIB +07
:00]]
←[1m←[35mAuditStatus Load (1.0ms)←[0m SELECT "audit_statuses".* FROM "audit_statuses" WHERE "audi
t_statuses"."id" = 1 LIMIT 1
←[1m←[36mSQL (2.0ms)←[0m ←[1mUPDATE "audit_statuses" SET "count_audit" = COALESCE("count_audit",
0) + 1 WHERE "audit_statuses"."id" = 1←[0m
←[1m←[35m (1.0ms)←[0m COMMIT
=> #<Audit id: 1, audit_status_id: 1, status: true, created_at: "2014-06-06 08:19:00", updated_at: "
2014-06-06 08:19:00">
irb(main):003:0> audit = Audit.create!({:audit_status_id => audit_status.id, :status => false})
←[1m←[36m (1.0ms)←[0m ←[1mBEGIN←[0m
←[1m←[35mSQL (1.0ms)←[0m INSERT INTO "audits" ("audit_status_id", "created_at", "status", "update
d_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["audit_status_id", 1], ["created_at", Fri, 06 Jun 2
014 15:19:23 WIB +07:00], ["status", false], ["updated_at", Fri, 06 Jun 2014 15:19:23 WIB +07:00]]
←[1m←[36mAuditStatus Load (1.0ms)←[0m ←[1mSELECT "audit_statuses".* FROM "audit_statuses" WHERE "
audit_statuses"."id" = 1 LIMIT 1←[0m
←[1m←[35mSQL (0.0ms)←[0m UPDATE "audit_statuses" SET "count_audit" = COALESCE("count_audit", 0) +
1 WHERE "audit_statuses"."id" = 1
←[1m←[36m (0.0ms)←[0m ←[1mCOMMIT←[0m
=> #<Audit id: 2, audit_status_id: 1, status: false, created_at: "2014-06-06 08:19:23", updated_at:
"2014-06-06 08:19:23">
So, you only call audit_status's records looks like :
irb(main):004:0> #audit_statuses = AuditStatus.all
←[1m←[35mAuditStatus Load (1.0ms)←[0m SELECT "audit_statuses".* FROM "audit_statuses"
=> [#<AuditStatus id: 1, name: "John Noe", count_audit: 2, created_at: "2014-06-06 08:17:49", update
d_at: "2014-06-06 08:17:49">]
#audit_status = Audit.joins( :audit_status).select("name as status,count(audit_status_id) as count").group(:name)

Where do tags save in acts_as_taggable_on

Ok, I'm trying to keep things simple here and do testing in the rails console.. However, I can't seem to figure out how to save tags and read them out again. As you can see from the paste below, I can't save the #consumer object (with tags) and then read out the tags..
http://pastebin.com/txpuf09g
1.9.3p286 :001 > #consumer = Consumer.first
Creating scope :page. Overwriting existing method Consumer.page.
Consumer Load (1.3ms) SELECT "consumers".* FROM "consumers" LIMIT 1
=> #<Consumer id: 29, hl: nil, created_at: "2012-10-27 23:27:15", updated_at: "2012-10-27 23:27:15", user_id: 33, display_name: nil, tagline: nil, desc: nil>
1.9.3p286 :002 > #consumer.tags
ActsAsTaggableOn::Tag Load (2.3ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = 29 AND "taggings"."taggable_type" = 'Consumer' AND (taggings.context = 'tags')
=> []
1.9.3p286 :003 > #consumer.tag_list
ActsAsTaggableOn::Tag Load (1.4ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = 29 AND "taggings"."taggable_type" = 'Consumer' AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)
=> []
1.9.3p286 :004 > #consumer.tag_list = "hi, ho"
=> "hi, ho"
1.9.3p286 :005 > #consumer
=> #<Consumer id: 29, hl: nil, created_at: "2012-10-27 23:27:15", updated_at: "2012-10-27 23:27:15", user_id: 33, display_name: nil, tagline: nil, desc: nil>
1.9.3p286 :006 > #consumer.save
(0.4ms) BEGIN
(0.7ms) UPDATE "consumers" SET "updated_at" = '2013-02-15 00:25:05.187733' WHERE "consumers"."id" = 29
ActsAsTaggableOn::Tag Load (0.8ms) SELECT "tags".* FROM "tags" WHERE (lower(name) = 'hi' OR lower(name) = 'ho')
ActsAsTaggableOn::Tag Exists (0.6ms) SELECT 1 AS one FROM "tags" WHERE "tags"."name" = 'hi' LIMIT 1
SQL (1.3ms) INSERT INTO "tags" ("name") VALUES ($1) RETURNING "id" [["name", "hi"]]
ActsAsTaggableOn::Tag Exists (0.5ms) SELECT 1 AS one FROM "tags" WHERE "tags"."name" = 'ho' LIMIT 1
SQL (0.4ms) INSERT INTO "tags" ("name") VALUES ($1) RETURNING "id" [["name", "ho"]]
ActsAsTaggableOn::Tag Load (0.7ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = 29 AND "taggings"."taggable_type" = 'Consumer' AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)
ActsAsTaggableOn::Tagging Exists (0.7ms) SELECT 1 AS one FROM "taggings" WHERE ("taggings"."tag_id" = 5 AND "taggings"."taggable_type" = 'Consumer' AND "taggings"."taggable_id" = 29 AND "taggings"."context" = 'tags' AND "taggings"."tagger_id" IS NULL AND "taggings"."tagger_type" IS NULL) LIMIT 1
SQL (1.5ms) INSERT INTO "taggings" ("context", "created_at", "tag_id", "taggable_id", "taggable_type", "tagger_id", "tagger_type") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["context", "tags"], ["created_at", Fri, 15 Feb 2013 00:25:05 UTC +00:00], ["tag_id", 5], ["taggable_id", 29], ["taggable_type", "Consumer"], ["tagger_id", nil], ["tagger_type", nil]]
ActsAsTaggableOn::Tagging Exists (0.7ms) SELECT 1 AS one FROM "taggings" WHERE ("taggings"."tag_id" = 6 AND "taggings"."taggable_type" = 'Consumer' AND "taggings"."taggable_id" = 29 AND "taggings"."context" = 'tags' AND "taggings"."tagger_id" IS NULL AND "taggings"."tagger_type" IS NULL) LIMIT 1
SQL (0.5ms) INSERT INTO "taggings" ("context", "created_at", "tag_id", "taggable_id", "taggable_type", "tagger_id", "tagger_type") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["context", "tags"], ["created_at", Fri, 15 Feb 2013 00:25:05 UTC +00:00], ["tag_id", 6], ["taggable_id", 29], ["taggable_type", "Consumer"], ["tagger_id", nil], ["tagger_type", nil]]
(11.9ms) COMMIT
=> true
1.9.3p286 :007 > Consumer.first.tags
Consumer Load (0.9ms) SELECT "consumers".* FROM "consumers" LIMIT 1
ActsAsTaggableOn::Tag Load (1.0ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = 30 AND "taggings"."taggable_type" = 'Consumer' AND (taggings.context = 'tags')
=> []
Also, I can't find tags or taggings as a table in my DB. Thanks for helping me to understand this.
EDIT:
I think I see the problem.. in the taggings table I am seeing id, tag_id, taggable_id, taggable_type, tagger_id, tagger_type, context columns.. the rows seem complete with the exception of tagger_id and tagger_type. Do you think this has anything to do with the tags not being associated with the consumer's id? I guess the question is, where should the Consumer.id actually be appearing in the taggings table.. At the moment the Consumer.first.id is not in any of the columns in taggings! The Consumer.first.id == 30
try appending to the array of the tags_list via
#consumer.tag_list << "foo"
#consumber.save
then save
Also acts_as_taggable_on does create a tabled called tags in your case. You may want to run a migration if your not seeing it.

How to sanitize strings for storage in a sqlite database?

I'm trying to store tags from mp3's in a sqlite database and I get the following error:
SQL (0.3ms) INSERT INTO "songs" ("album", "artist", "created_at", "length", "path", "store_id", "title", "track_number", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) [["album", "\xFF\xFE2\x001\x00"], ["artist", "\xFF\xFEa\x00d\x00e\x00l\x00e\x00"], ["created_at", Tue, 24 Jul 2012 03:34:03 UTC +00:00], ["length", 15], ["path", "/audios/music/Adele - Discography (Complete) [2008 - 2011]/Adele - 21 [2011] + Bonus Tracks/01. Adele - Rolling in the Deep.mp3"], ["store_id", 3], ["title", "\xFF\xFEr\x00o\x00l\x00l\x00i\x00n\x00g\x00 \x00i\x00n\x00 \x00t\x00h\x00e\x00 \x00d\x00e\x00e\x00p\x00"], ["track_number", "01"], ["updated_at", Tue, 24 Jul 2012 03:34:03 UTC +00:00]]
Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8: INSERT INTO "songs" ("album", "artist", "created_at", "length", "path", "store_id", "title", "track_number", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
(0.2ms) rollback transaction
ActiveRecord::StatementInvalid: Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8: INSERT INTO "songs" ("album", "artist", "created_at", "length", "path", "store_id", "title", "track_number", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
How could I strip or sanitize the input?
ActiveRecord complains about Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8, but it obvious that \xFF\xFE2\x001\x00 is not in ASCII-8BIT encoding. So, you can fix this by converting id3 tags to UTF-8 before calling ActiveRecord.
"source string".encoding(dst_encoding, src_encoding).
Documentation: http://www.ruby-doc.org/core-1.9.3/String.html#method-i-encode

Resources