form submitting twice with :remote => true Rails 3.2 - forms

I have the following form:
= form_for([current_user,#company], :remote => true) do |f|
-if #company.errors.any?
#error_explanation
%h2= "#{pluralize(#company.errors.count, "error")} prohibited this company from being saved:"
%ul
- #company.errors.full_messages.each do |msg|
%li= msg
=f.label :name
=f.text_field :name
=f.label :address
=f.text_area :address, :rows => 3, :cols => 5
=f.label :phone_number
=f.text_field :phone_number
.actions
= f.submit 'Save'
When I click the save button I can see the folllowing in my server log:
Started POST "/users/1/companies" for 127.0.0.1 at 2012-04-04 21:27:50 +0700
Processing by CompaniesController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6ZH9hAUuf5ZTCf8Loc4M/IIl/Etzm7uDGoYbIgCTvhI=", "company"=>{"name"=>"test", "address"=>"test", "phone_number"=>"5454543"}, "commit"=>"Save", "user_id"=>"1"}
(0.2ms) BEGIN
SQL (25.2ms) INSERT INTO "companies" ("address", "name", "phone_number", "url", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["address", "test"], ["name", "test"], ["phone_number", "5454543"], ["url", nil], ["user_id", nil]]
(1.6ms) COMMIT
Rendered companies/create.js.erb (0.7ms)
Completed 200 OK in 41ms (Views: 8.1ms | ActiveRecord: 27.0ms)
Started POST "/users/1/companies" for 127.0.0.1 at 2012-04-04 21:27:50 +0700
Processing by CompaniesController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6ZH9hAUuf5ZTCf8Loc4M/IIl/Etzm7uDGoYbIgCTvhI=", "company"=>{"name"=>"test", "address"=>"test", "phone_number"=>"5454543"}, "commit"=>"Save", "user_id"=>"1"}
(0.7ms) BEGIN
SQL (2.7ms) INSERT INTO "companies" ("address", "name", "phone_number", "url", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["address", "test"], ["name", "test"], ["phone_number", "5454543"], ["url", nil], ["user_id", nil]]
(12.8ms) COMMIT
Rendered companies/create.js.erb (0.1ms)
Completed 200 OK in 30ms (Views: 10.5ms | ActiveRecord: 16.1ms)
Which means the form is being submitted twice.
I have removed the assets folder from my public directory. I have also checked the html rendered on the page and there is no double inclusion of jquery or other dependencies.
Why is it being submitted twice?

i had run rake assets:precompile and was running my server in development mode. solution was to rake assets:clean and restart the sever

My workaround for this:
rake assets:precompile
with //= require jquery_ujs in your app/assets/javascripts/application.js
After the rake, remove the line from app/assets/javascripts/application.js and start the server.
Now it should work as expected.

Related

symfony - configure postgres entity manager

I would like to change the database in my existing project from mysql to postgresql.
I have configured the database, I have regenerated the migrations which work, but the problem appears in the fixtures.
when trying to load fixtures an error appears like this:
An exception occurred while executing 'INSERT INTO user (nickname, password, id, created_at, updated_at, email) VALUES (?, ?, ?, ?, ?, ?)' with params ["user", "$2y$13$rgHtT56Vlk2
avmf3gX2W7.QYcQ5d6AXRzr41ebRMGfxREqLZQfsTG", "017c4562-d487-ddff-c303-108c1916d6dd", "2021-10-03 11:01:16", "2021-10-03 11:01:16", "user#user.pl"]:
SQLSTATE[42601]: Syntax error: 7 BŁĄD: błąd składni w lub blisko "user"
LINE 1: INSERT INTO user (nickname, password, id, created_at, update... ,
this is a problem possibly caused by entity manager generating the mysql dialect instead of postgres dialect.
a similar error occurs during the get shot under the user entity:
"hydra:description": "An exception occurred while executing 'SELECT u0_.nickname AS nickname_0, u0_.password AS password_1, u0_.id AS id_2, u0_.created_at AS created_at_3, u0_.updated_at AS updated_at_4, u0_.email AS email_5 FROM user u0_':\n\nSQLSTATE[42703]: Undefined column: 7 BŁĄD: kolumna u0_.nickname nie istnieje\nLINE 1: SELECT u0_.nickname AS nickname_0, u0_.password AS password_.
Here is my doctrine.yaml configuration:
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL)%'
driver: 'pdo_pgsql'
charset: utf8
# IMPORTANT: You MUST configure your server version,
# either here or in the DATABASE_URL env var (see .env file)
#server_version: '13'
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
auto_mapping: true
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
Could someone help me get rid of the bug? :)

Create a model that belongs_to another in Rails 5

This is my image model:
class Image < ApplicationRecord
belongs_to :user
mount_uploader :avatar, AvatarUploader
end
I can't even create an image in console without a user? Did this change from Rails 4?
Image.create
(0.1ms) begin transaction
(0.1ms) rollback transaction
=> #<Image id: nil, user_id: nil, title: nil, created_at: nil, updated_at: nil, avatar: nil>
2.2.4 :018 > Image.create(title: "hi")
(0.3ms) begin transaction
(0.1ms) rollback transaction
=> #<Image id: nil, user_id: nil, title: "hi", created_at: nil, updated_at: nil, avatar: nil>
2.2.4 :019 > u = User.create
(0.1ms) begin transaction
SQL (0.2ms) INSERT INTO "users" ("created_at", "updated_at") VALUES (?, ?) [["created_at", 2016-03-17 04:27:09 UTC], ["updated_at", 2016-03-17 04:27:09 UTC]]
(8.6ms) commit transaction
=> #<User id: 6, name: nil, created_at: "2016-03-17 04:27:09", updated_at: "2016-03-17 04:27:09">
2.2.4 :020 > u.images << Image.create
(0.1ms) begin transaction
(0.0ms) rollback transaction
(0.0ms) begin transaction
SQL (0.3ms) INSERT INTO "images" ("user_id", "created_at", "updated_at") VALUES (?, ?, ?) [["user_id", 6], ["created_at", 2016-03-17 04:27:16 UTC], ["updated_at", 2016-03-17 04:27:16 UTC]]
(7.8ms) commit transaction
Image Load (0.2ms) SELECT "images".* FROM "images" WHERE "images"."user_id" = ? [["user_id", 6]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Image id: 3, user_id: 6, title: nil, created_at: "2016-03-17 04:27:16", updated_at: "2016-03-17 04:27:16", avatar: nil>]>
I can't get my factories setup:
FactoryGirl.define do
factory :user do
sequence(:name) { |n| "jeff#{n}" }
after(:build) do |user, eval|
user.images << build(:image)
end
end
factory :image do
avatar File.open(File.join(Rails.root, '/spec/support/images/blueapron.jpg'))
end
end
These are my error messsages:
* image - Validation failed: User must exist (ActiveRecord::RecordInvalid)
from /Users/Jwan/.rvm/gems/ruby-2.2.4/gems/factory_girl-4.5.0/lib/factory_girl/linter.rb:4:in `lint!'
from /Users/Jwan/.rvm/gems/ruby-2.2.4/gems/factory_girl-4.5.0/lib/factory_girl.rb:59:in `lint'
from /Users/Jwan/Dropbox/programming/rails/carrierwave_s3/spec/support/factory_girl.rb:10:in `block (2
Yes it changed in rails 5. If you need previous behavior, add optional: true to the belongs_to declaration.

Knex.js SQL syntax error near 'select'

I'm getting an odd error:
{ __cid: '__cid9',
method: 'insert',
options: undefined,
bindings:
[ 500,
'Dinner',
'10/02/2015 7:57 PM',
'09/29/2015 8:00 PM',
'Grand Plaza',
1 ],
sql: 'insert into "expense" ("amount", "description", "due_date", "payment_date", "vendor_id") values ($1, $2, $3, $4, select "vendor_id" from "vendor" where "name" = $5 limit $6)',
returning: undefined }
error: syntax error at or near "select"
at [object Object].Connection.parseE (/.../node_modules/pg/lib/connection.js:534:11)
at [object Object].Connection.parseMessage (/.../node_modules/pg/lib/connection.js:361:17)
at Socket.<anonymous> (/.../node_modules/pg/lib/connection.js:105:22)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
I have run the raw SQL with those value cut and paste and it works just fine.
This is the code thats generating the error:
Promise.each subbudget.expenses, (expense) ->
vendor.get(expense.vendor).then (vendor_id) ->
knex('expense').insert(
due_date: expense.dueDate
vendor_id: (knex.first("vendor_id").from("vendor").where({name: vendor_id}))
amount: expense.amount
description: expense.description
payment_date: expense.paidDate
)
Edit (Partial Solution):
The issue seems to be parentheses missing around the SELECT statement. Knex offers .wrap(), which only works on raw, and .as(), which only works on nested statements; for some reason this does not qualify as a nested statement, so I can't get parentheses around it. Any ideas?
knex.raw("(" + knex.first("vendor_id").from("vendor").where({name: vendor_id}).toString() + ")")
Not the cleanest, but use .toString(), then wrap it in .raw()

Sails.js + Postgres: issue with transactions

I am trying to implement a transaction in Sails 0.10.5 using Postgres as database, but the operations are not committed (or rolled back) at the end.
This is a simple transaction scenario I wrote down as a test (using async.js):
testTransaction: function(uri) {
var testFile = {
uri: uri,
details: { 'firstDetail': 'value' }
};
async.auto({
begin_transaction: function(callback) {
DataFile.query('BEGIN TRANSACTION;', callback);
},
new_data_file: ['begin_transaction', function(callback) {
DataFile.create(testFile).exec(callback);
}],
}, function(error, results) {
if (error) {
console.log(error.message);
DataFile.query('ROLLBACK;', function(e, r) {
return error.message;
});
return;
}
DataFile.query('COMMIT;', function(e, r) {
console.log("Saved file: " + results.new_data_file);
if (e) {
return "Error during commit";
}
return results.new_data_file;
});
});
}
Then I run the service without errors; but no new DataFile enetity is added to the Postgres table. If I check the Postgres log, I find out that:
2014-12-04 10:35:01 GMT 7984 548038d0.1f30LOG: statement: BEGIN TRANSACTION;
2014-12-04 10:35:01 GMT 7977 548038d0.1f29LOG: execute <unnamed>: INSERT INTO "data_file" ("uri", "details", "created_at", "updated_at") values ($1, $2, $3, $4) RETURNING *
2014-12-04 10:35:01 GMT 7977 548038d0.1f29DETAIL: parameters: $1 = '/just/another/test/uri', $2 = '{"firstDetail":"value"}', $3 = '2014-12-04 10:35:01+00', $4 = '2014-12-04 10:35:01+00'
2014-12-04 10:35:01 GMT 7983 548038d0.1f2fLOG: statement: COMMIT;
2014-12-04 10:35:01 GMT 7983 548038d0.1f2fWARNING: there is no transaction in progress
So I get the warning: "there is no transaction in progress"
The third element on the log is the Process ID.
Apparently the COMMIT statement is issued by a different process (7983) than the one that issued the BEGIN (7984). Might this be the issue?. How can I force to use the same process when dealing with transactions in Sails?
Transactions rely on several queries being made with the same connection, but Waterline uses a different connection for every query, which is why you're getting the "there is no transaction in progress" message - the second query is using a different connection, which doesn't have an in-progress transaction.
There's no way to work around this, other than to set the poolSize to 1 (so every query must use the same connection).
Here's the library we use for transactions - https://github.com/Shyp/pg-transactions. You won't have access to the helper methods - .find(), .update() etc but at least it's possible.

How do I whitelist these Rails4 params?

I am using this in my controller:
def step_params
params.require(#type.underscore.to_sym).permit(
:id, :name, :note, :position, :institution_id, :protocol_id, :sequence_id,:orientation_id,
step_item_attributes: [:id, :note, :name, :position, :institution_id, :sequence_id, :orientation_id, :_destroy ],
step_list_attributes: [:id, :note, :name, :position, :institution_id, :sequence_id, :orientation_id, :_destroy ])
end
And see this in the server log after a form with nested attributes is submitted:
Processing by StepsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xm6oMMJ2PLXhHfKS1RkIzG5LrCUAY6vLOF+e9XHgBE4=", "step_list"=>{"name"=>"bob bob", "note"=>"", "step_items_attributes"=>{"1411264481612"=>{"name"=>"", "orientation_id"=>"1", "sequence_id"=>"1", "note"=>"a note", "_destroy"=>"false"}}}, "commit"=>"Create Step list", "type"=>"StepList"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Unpermitted parameters: step_items_attributes
(0.1ms) begin transaction
SQL (0.7ms) INSERT INTO "steps" ("created_at", "institution_id", "name", "note", "updated_at") VALUES (?, ?, ?, ?, ?) [["created_at", "2014-09-21 01:54:49.736556"], ["institution_id", 18], ["name", "bob bob"], ["note", ""], ["updated_at", "2014-09-21 01:54:49.736556"]]
(37.5ms) commit transaction
Redirected to http://localhost:3000/steps/54
Completed 302 Found in 47ms (ActiveRecord: 38.7ms)
Looks to me like "Unpermitted parameters: step_items_attributes"
... is the problem.
Why does my permit method not allow the step_items_attributes hash? How could I figure out what other notation might work?
Your permitted Items sets step_item_attributes but you trying to pass step_items_attributes (items) with an 's'. so that's why you get Unpermitted parameters: step_items_attributes