CarrierWave. Impossible to save the file with STI - ruby-on-rails

I have model Document:
class Document < ActiveRecord::Base
belongs_to :company
validates :name, :presence => true
end
And two classes inherited from Document:
License:
class License < Document
mount_uploader :file, DocumentUploader
end
And Certificate
class Certificate < Document
mount_uploader :file, DocumentUploader
end
And when I try to do current_company.licenses.create(...) or same action for the certificate, always all params are saved, besides file, which always is nil
Also I've tried to mount file inside of Document model... Help me please.
Here is logs:
Started POST "/companies/1/verified" for 127.0.0.1 at Mon Mar 19 09:33:41 +0200 2012
Processing by CompaniesController#verified as HTML
Parameters: {"verified"=>{"certificate"=>{"name"=>"Certificate", "file"=>"test.png"}, "insured"=>"2000000", "suppliers"=>"", "license"=>{"name"=>"License", "file"=>"test.png"}}, "authenticity_token"=>"0hIn41Tjonm/AXZBKM1PE/tjQxJDLqZaojMTHDoZq2k=", "id"=>"1", "utf8"=>"✓", "commit"=>"Update verifications"}
Company Load (0.7ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = 1 LIMIT 1
(0.1ms) BEGIN
SQL (0.8ms) INSERT INTO "documents" ("company_id", "created_at", "file", "name", "type", "updated_at", "verified") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["company_id", 1], ["created_at", Mon, 19 Mar 2012 07:33:41 UTC +00:00], ["file", nil], ["name", "License"], ["type", "License"], ["updated_at", Mon, 19 Mar 2012 07:33:41 UTC +00:00], ["verified", false]]
(0.6ms) COMMIT
(0.1ms) BEGIN
SQL (0.5ms) INSERT INTO "documents" ("company_id", "created_at", "file", "name", "type", "updated_at", "verified") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["company_id", 1], ["created_at", Mon, 19 Mar 2012 07:33:41 UTC +00:00], ["file", nil], ["name", "Certificate"], ["type", "Certificate"], ["updated_at", Mon, 19 Mar 2012 07:33:41 UTC +00:00], ["verified", false]]
(0.4ms) COMMIT
Redirected to http://localhost:3000/company/profile
Completed 302 Found in 18ms (ActiveRecord: 3.3ms)
Thanks.

Are you sure you've set the form that you've uploading the file with to have a multipart payload?
If not the file won't get sent on submission, and rails will only receive the textual form data. Inside the form_helper tag you'll need to add.
:html => {:multipart => true}

Related

Why some model attributes not saved in the db?

I have a Quote model in my rails app which has various attr types, some of which are being sent to / saved by the db, some are not and I cannot understand why. Please can you help me understand, thanks.
quotes_controller.rb
class QuotesController < ApplicationController
def create
#quote = Quote.new(quote_params)
if #quote.save
redirect_to root_url, notice: 'Quote request created'
else
render :new
end
end
private
def quote_params
params.require(:quote).permit(:gla, :prev_cover, :co_name, :postcode, :industry, :lives_overseas,
:scheme_start_date, :payment_frequency, :commision_level)
end
end
quote.rb model
class Quote < ApplicationRecord
validates :gla, presence: { message: "Must be selected" }
enum industry: [ :financial_services, :architect, :business_consultancy ]
enum payment_frequency: [ :annually, :monthly ]
end
schema.rb
create_table "quotes", force: :cascade do |t|
t.boolean "prev_cover"
t.string "co_name"
t.integer "co_number"
t.string "postcode"
t.string "industry"
t.boolean "lives_overseas"
t.date "scheme_start_date"
t.string "payment_frequency"
t.integer "commission_level"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "gla"
end
rails console:
Pry> Quote.last.attributes
Quote Load (0.4ms) SELECT "quotes".* FROM "quotes" ORDER BY "quotes"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> {"id"=>6,
"prev_cover"=>true,
"co_name"=>"test1",
"co_number"=>nil,
"postcode"=>"al1 1aa",
"industry"=>nil,
"lives_overseas"=>true,
"scheme_start_date"=>Wed, 31 May 2017,
"payment_frequency"=>nil,
"commission_level"=>nil,
"created_at"=>Wed, 31 May 2017 19:23:07 UTC +00:00,
"updated_at"=>Wed, 31 May 2017 19:23:07 UTC +00:00,
"gla"=>true}
Stack Trace:
Started POST "/quotes" for 127.0.0.1 at 2017-05-31 21:04:37 +0100
Processing by QuotesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ILAo0Bs9Wq9lrVPlM2e6+a1kioV9zbni9Uxd5Yt/QSLNY3aVWyJ4TsEUmXN62RWgbueHksr/yN6avwEm8v7bEQ==", "quote"=>{"gla"=>"1", "prev_cover"=>"true", "co_name"=>"testing1", "co_number"=>"123456", "postcode"=>"al1 1aa", "industry"=>"", "lives_overseas"=>"true", "scheme_start_date(1i)"=>"2017", "scheme_start_date(2i)"=>"5", "scheme_start_date(3i)"=>"31", "payment_frequency"=>"", "commission_level"=>"10"}, "commit"=>"Get quote"}
Unpermitted parameters: co_number, commission_level
(0.1ms) BEGIN
SQL (0.2ms) INSERT INTO "quotes" ("prev_cover", "co_name", "postcode", "lives_overseas", "scheme_start_date", "created_at", "updated_at", "gla") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id" [["prev_cover", "t"], ["co_name", "testing1"], ["postcode", "al1 1aa"], ["lives_overseas", "t"], ["scheme_start_date", "2017-05-31"], ["created_at", "2017-05-31 20:04:37.489368"], ["updated_at", "2017-05-31 20:04:37.489368"], ["gla", "t"]]
(0.3ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 3ms (ActiveRecord: 0.6ms)
Started GET "/" for 127.0.0.1 at 2017-05-31 21:04:37 +0100
Processing by QuotesController#new as HTML
Rendering quotes/new.html.erb within layouts/application
Rendered quotes/new.html.erb within layouts/application (9.3ms)
Completed 200 OK in 34ms (Views: 32.7ms | ActiveRecord: 0.0ms)
From Rails console.
[1] pry(main)> Quote.last
Quote Load (0.2ms) SELECT "quotes".* FROM "quotes" ORDER BY "quotes"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Quote:0x007f951b14e918
id: 7,
prev_cover: true,
co_name: "testing1",
co_number: nil,
postcode: "al1 1aa",
industry: nil,
lives_overseas: true,
scheme_start_date: Wed, 31 May 2017,
payment_frequency: nil,
commission_level: nil,
created_at: Wed, 31 May 2017 20:04:37 UTC +00:00,
updated_at: Wed, 31 May 2017 20:04:37 UTC +00:00,
gla: true>
Ok stack trace and #toddmetheny help me sort out the missing or typo'd permitted attrs. Now just the enums Quote.industries and Quote.payment_frequencies whose values aren't getting saved.
Ok, so code changed to;
And this sends the attrs from the form, but they still don't get created in the db, stack trace:
Started POST "/quotes" for 127.0.0.1 at 2017-05-31 21:39:58 +0100
Processing by QuotesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"rkgX7CwrEHS/KnqG1C77mYkCiCEOWGshTxMCsbtGPdjGiDP20J4ccrAgplAGuKrdJyhECRWrsmXI0Ee9GNa6Zw==", "quote"=>{"gla"=>"1", "prev_cover"=>"true", "co_name"=>"halejulia", "co_number"=>"134532", "postcode"=>"al1 1aa", "industry"=>"financial_services", "lives_overseas"=>"true", "scheme_start_date(1i)"=>"2017", "scheme_start_date(2i)"=>"5", "scheme_start_date(3i)"=>"31", "payment_frequency"=>"monthly", "commission_level"=>"10"}, "commit"=>"Get quote"}
(0.1ms) BEGIN
SQL (0.3ms) INSERT INTO "quotes" ("prev_cover", "co_name", "co_number", "postcode", "industry", "lives_overseas", "scheme_start_date", "payment_frequency", "commission_level", "created_at", "updated_at", "gla") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id" [["prev_cover", "t"], ["co_name", "halejulia"], ["co_number", 134532], ["postcode", "al1 1aa"], ["industry", 0], ["lives_overseas", "t"], ["scheme_start_date", "2017-05-31"], ["payment_frequency", 1], ["commission_level", 10], ["created_at", "2017-05-31 20:39:58.957674"], ["updated_at", "2017-05-31 20:39:58.957674"], ["gla", "t"]]
(0.3ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 3ms (ActiveRecord: 0.7ms)
rails console :
Quote.last.payment_frequency
Quote Load (0.4ms) SELECT "quotes".* FROM "quotes" ORDER BY "quotes"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> nil
So still the params aren't being persisted in the db, they're permitted params! any ideas?
Strange, a psql select * from .. query shows that the values have been saved, yet Rails console; Quote.last.payment_frequency returns nil???
Aha, i see that for a enum the column type should be integer, yet it is string in my model, could this be the issue perhaps?
Data type of enum'd attrs changed to integer and all behaves as expected.
Post the stack trace. co_number isn't whitelisted in the permitted params. So that's at least part of the issue with that particular field. The others are...but post what you're actually seeing in the logs so we can see what's being passed through the form. There will also be messages in the stack trace that give you clues as to why those values aren't saving.
Update: the stack trace lists 2 unpermitted parameters: co_number and commission_level (you have a typo permitting commission level and co_number isn't there)
A couple things have blank values, too...like payment_frequency and industry...I'd dig into why those things are blank if they shouldn't be. Does the form have values for those things? They aren't being passed. That seems to account for the rest of your nil values.

How globalize gem decides which content goes to translated table?

In my rails 4.2 app I have set it as the default locale by setting it in config/application.rb:
config.i18n.default_locale = :it
I have a simple "product" model
class Product < ActiveRecord::Base
translates :name, :description
end
My need is when I18n.locale = :it the content should be written in "products" table while for all others locales the content shoud go in the "product_translations" table.
Currently what happens is the following:
if
config.i18n.default_locale = :en
content is written to the "products" table, for all different locales the content goes to the "product_translations" table.
How can I change this?
EDIT
Using the console to test globalize behaviour I found that maybe I did not understand how globalize should work.
I was expecting that the "products" table is filled with default_locale (in my case :it) and the "product_translations" table is filled with other locales (:en, :fr, :de and so on).
Instead I see that whichever the locale is, fields that are indicated as
translates :name, :description
are always written in "product_translations" and "product" table only contains those fields that are not translated (in my case uom (unit of measure).
This is the output of the console after saving a new product with :en as locale.
[18] pry(main)> en_p=Product.create(:name=>"butter",
:description => "82% min fat butter",
:uom => "kg") (0.3ms)
BEGIN
SQL (0.7ms)
INSERT INTO "products" ("uom", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"
[
["uom", "kg"],
["created_at", "2015-07-14 05:49:09.097092"],
["updated_at", "2015-07-14 05:49:09.097092"]
]
SQL (0.7ms)
INSERT INTO "product_translations" ("locale",
"name",
"description",
"product_id",
"created_at",
"updated_at")
VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"
[
["locale", "en"],
["name", "butter"],
["description", "82% min fat butter"],
["product_id", 5],
["created_at", "2015-07-14 05:49:09.116683"],
["updated_at", "2015-07-14 05:49:09.116683"]
]
(15.9ms)
COMMIT
=> #<Product:0xb63d3568
id: 5,
name: "butter",
description: "82% min fat butter",
uom: "kg",
created_at: Tue, 14 Jul 2015 05:49:09 UTC +00:00,
updated_at: Tue, 14 Jul 2015 05:49:09 UTC +00:00>
[19] pry(main)> I18n.locale=:it
=> :it
[20] pry(main)> it_p=Product.create(:name=>"olio di oliva EVO",
:description => "Olio di oliva extravergine spremuto a freddo",
:uom => "kg") (0.4ms)
BEGIN
SQL (0.5ms)
INSERT INTO "products" ("uom", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"
[
["uom", "kg"],
["created_at", "2015-07-14 05:51:34.772755"],
["updated_at", "2015-07-14 05:51:34.772755"]
]
SQL (0.8ms)
INSERT INTO "product_translations" ("locale",
"name",
"description",
"product_id",
"created_at",
"updated_at")
VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"
[
["locale", "it"],
["name", "olio di oliva extravergine"],
["description", "Olio di oliva extravergine ottenuto unicamente per spremitura"],
["product_id", 6],
["created_at", "2015-07-14 05:51:34.779220"],
["updated_at", "2015-07-14 05:51:34.779220"]
]
(16.1ms)
COMMIT
=> #<Product:0xb6315ce8
id: 6,
name: "olio di oliva extravergine",
description: "Olio di oliva extravergine ottenuto unicamente per spremitura",
uom: "kg",
created_at: Tue, 14 Jul 2015 05:51:34 UTC +00:00,
updated_at: Tue, 14 Jul 2015 05:51:34 UTC +00:00>
Is this the default behaviour?
Do I need to remove translatable fields from the original table?

has_many through middle model not creating, but creating duplicate of one model

I have two models join by a middle model
class Integration < ActiveRecord::Base
has_many :integration_records
has_many :records, through: :integration_records
end
class IntegrationRecord < ActiveRecord::Base
belongs_to :integration
belongs_to :record
end
class Record < ActiveRecord::Base
has_many :integration_records
has_many :integrations, through: :integration_records
end
i = Integration.create(whatever)
i.records.create(whatever)
=> (0.1ms) BEGIN
SQL (8.7ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:02 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:02 UTC +00:00]]
SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:06 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:06 UTC +00:00]]
(0.4ms) COMMIT
i.records
=> [one record]
Record.all.count
=> 2
i.integration_records
=> #<IntegrationRecord id: nil, integration_id: 1, record_id: 2 >
Notice id is nil
IntegrationRecord.all
=> #<ActiveRecord::Relation []>
IntegrationRecord.create
=> #<IntegrationRecord id: nil, integration_id: nil, record_id: nil>
Notice id is nil
Record.create.integrations.create
=> (0.1ms) BEGIN
SQL (8.7ms) INSERT INTO "integrations" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:02 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:02 UTC +00:00]]
SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:06 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:06 UTC +00:00]]
(0.4ms) COMMIT
Not sure why this is happening, in the case of i.records.create(whatever) it should output:
SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:06 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:06 UTC +00:00]]
(0.4ms) COMMIT
INSERT INTO "integration_records" ("created_at", "data", "integration_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Sat, 03 May 2014 15:57:05 UTC +00:00], ["data", {}], ["integration_id", 5], ["updated_at", Sat, 03 May 2014 15:57:05 UTC +00:00]]
I should note that for some reason, when I create a new app in rails 4.0.4, I still had this problem. But when I change the names of the models and specifically Record model, it works perfectly fine. So when I changed it to Recordrow no problem at all.
As per your current association setup, all you need to do is, just follow these simple instructions step by step
Create an Integration record
## this will create an "integration" record in "integrations" table
integration = Integration.create(whatever)
Create an associated Record record
## this will create an associated "record" entry in "records" table
## PLUS this will also created an associated record in "integration_records" table
integration.records.create(whatever)
View the associated records and associated integration_records
## Display all the "records" entries associated to this particular integration
integration.records
## Display all the "integration_records" entries associated to this particular integration
integration.integration_records
UPDATE
i.records.create(whatever) was creating 2 records, found out that the issue was with the name records of the table. Once changed everything works fine. It looks like records is reserved word.
Also, OP found this link which states records is reserved

Create action always creates two identical table entries instead of one

I have a create action in my ProductsController (the params come from a form in my view):
def create
vendor = #current_vendor
product = Product.create(:name => params[:product][:name])
vendor.products << product
vendor.belongings.create(:product_id => product.id, :count => params[:belonging][:count], :detail => params[:belonging][:detail])
if vendor.save
flash[:notice] = "Produkt hinzugefügt!"
redirect_back_or_default root_url
else
render :action => :new
end
end
It creates a variable "vendor", which stores the currently logged-in vendor (Authlogic)
A new Product is created (the product name is from the input field in the form) and stored in the variable "product"
The "product" is being connected to the current vendor
In the belongings table, additional informations to the product are being stored
it saves the whole thing
It's a many-to-many relationship throught the belongings table.
My problem is, the create action always creates the product twice!
Thanks for your help! :)
My console log when I create a new object through my form is:
Started POST "/products" for 127.0.0.1 at 2013-09-15 20:40:26 +0200
Processing by ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"lNk/qQMP0xhlCuGgHtU+d5NEvIlCFcPSKB0FxDZH0zY=", "product"=>{"name"=>"Erdbeeren"}, "belonging"=>{"count"=>"20", "detail"=>"Rot"}, "commit"=>"Create"}
DEPRECATION WARNING: ActiveRecord::Base#with_scope and #with_exclusive_scope are deprecated. Please use ActiveRecord::Relation#scoping instead. (You can use #merge to merge multiple scopes together.). (called from current_vendor_session at /Users/reto_gian/Desktop/dici/app/controllers/application_controller.rb:11)
Vendor Load (0.3ms) SELECT "vendors".* FROM "vendors" WHERE "vendors"."persistence_token" = '04f75db0e2ef108ddb0ae1be1da167536d47b4d79c60ecb443ad2ea5717ecd752388e581f9379746568c72372be4f08585aa5581915b1be64dc412cded73a705' LIMIT 1
(0.1ms) begin transaction
SQL (0.8ms) INSERT INTO "products" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["name", "Erdbeeren"], ["updated_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00]]
(0.8ms) commit transaction
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "belongings" ("created_at", "product_id", "updated_at", "vendor_id") VALUES (?, ?, ?, ?) [["created_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["product_id", 7], ["updated_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["vendor_id", 1]]
(0.9ms) commit transaction
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "belongings" ("count", "created_at", "detail", "product_id", "updated_at", "vendor_id") VALUES (?, ?, ?, ?, ?, ?) [["count", "20"], ["created_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["detail", "Rot"], ["product_id", 7], ["updated_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["vendor_id", 1]]
(0.9ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 30ms (ActiveRecord: 5.1ms)
I think the problem could be in the line
vendor.products << product
this is adding the variable product (which is Product.create(:name => params[:product][:name]) to vendor.products a second time - which is unnecessary and likely the source of your problem

Why is rails not inserting data during create, only nil? (New scaffold)

I had an annoying problem with a freshly generated scaffold. Everything would run nicely, but while I could enter data, everytime I tried to save he would commit nil successfully. For all fields.
Looks like this:
Started POST "/spraches" for 127.0.0.1 at 2012-08-26 23:34:03 +0200
Processing by SprachesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"nMf1+rBegI9BKoSAekzq8iLPQPAHpiiPk2DlmhEQxsQ=", "sprache"=>{"name"=>"23", "level"=>"23", "zertifikat"=>"124", "zertifikat_anders"=>"213", "zertifikat_note"=>"f23"}, "commit"=>"Create Sprache"}
[1m[36m (1.0ms)[0m [1mBEGIN[0m
[1m[35mSQL (29.0ms)[0m INSERT INTO "spraches" ("created_at", "level", "name", "updated_at", "zertifikat", "zertifikat_anders", "zertifikat_note") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["created_at", Sun, 26 Aug 2012 21:34:03 UTC +00:00], ["level", nil], ["name", nil], ["updated_at", Sun, 26 Aug 2012 21:34:03 UTC +00:00], ["zertifikat", nil], ["zertifikat_anders", nil], ["zertifikat_note", nil]]
[1m[36m (1.0ms)[0m [1mCOMMIT[0m
Redirected to http://localhost:3000/spraches/1
Completed 302 Found in 35ms (ActiveRecord: 31.0ms)
The reason become obivous to me after looking at the code in detail: I named my table in German (Sprache -> Language) and Rails tried to set it to plural. However, the controller only had it in the singular form.
#sprach = Sprache.new(params[:sprach])
I addded an "e" in the params to match the incoming code. Works.
The reason become obivous to me after looking at the code in detail: I named my table in German (Sprache -> Language) and Rails tried to set it to plural. However, the controller only had it in the singular form.
#sprach = Sprache.new(params[:sprach])
I addded an "e" in the params to match the incoming code. Works.

Resources