Validation for uniqueness not working - ruby-on-rails

I have a model called as Template which has self referential has-many through association with a join model called as RelatedTemplate.
The Template model is written like this:
has_many :related_templates, :foreign_key => :parent_id
has_many :children, :through => :related_templates, :source => :child
has_many :inverse_related_templates, class_name: "RelatedTemplate", :foreign_key => :child_id
has_many :parents, :through => :inverse_related_templates, :source => :parent
validates :name, presence: true, uniqueness: { case_sensitive: false },
length: { maximum: 100, too_long: "should be maximum %{count} characters" }
The join-model RelatedTemplate is:
belongs_to :parent, class_name: 'Template'
belongs_to :child, class_name: 'Template'
In the console when i tried to create a child template with the same name as the parent name then the validation doesn't work:
rails c --sandbox
Loading development environment in sandbox (Rails 4.2.5)
Any modifications you make will be rolled back on exit
irb(main):001:0> a = Template.new
=> #<Template id: nil, client_id: nil, something_id: nil, name: nil, description: nil, another_something_id: nil, video_id: nil, container_id: nil>
irb(main):002:0> a.something_id=1
=> 1
irb(main):003:0> a.name="Hamza"
=> "Hamza"
irb(main):004:0> a.another_something_id=16
=> 16
irb(main):005:0> a.container_id=2
=> 2
irb(main):006:0> a.children.build(name: "Hamza", another_something_id: 16, container_id: 2)
=> #<Template id: nil, client_id: nil, something_id: nil, name: "Hamza", description: nil, another_something_id: 16, video_id: nil, container_id: 2>
irb(main):007:0> a.save
(0.9ms) SAVEPOINT active_record_1
Template Exists (1.3ms) SELECT 1 AS one FROM "templates" WHERE LOWER("templates"."name") = LOWER('Hamza') LIMIT 1
Container Load (0.7ms) SELECT "containers".* FROM "containers" WHERE "containers"."id" = $1 LIMIT 1 [["id", 2]]
Template Exists (0.5ms) SELECT 1 AS one FROM "templates" WHERE LOWER("templates"."name") = LOWER('Hamza') LIMIT 1
Container Load (0.2ms) SELECT "containers".* FROM "containers" WHERE "containers"."id" = $1 LIMIT 1 [["id", 2]]
SQL (0.3ms) INSERT INTO "templates" ("something_id", "name", "another_something_id", "container_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["something_id", 1], ["name", "Hamza"], ["another_something_id", 16], ["container_id", 2]]
SQL (0.2ms) INSERT INTO "templates" ("name", "another_something_id", "container_id") VALUES ($1, $2, $3) RETURNING "id" [["name", "Hamza"], ["another_something_id", 16], ["container_id", 2]]
SQL (0.6ms) INSERT INTO "related_templates" ("parent_id", "child_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["parent_id", 156], ["child_id", 157], ["created_at", "2016-05-05 07:03:51.496346"], ["updated_at", "2016-05-05 07:03:51.496346"]]
(0.2ms) RELEASE SAVEPOINT active_record_1
=> true
Now the query:
irb(main):016:0> a.name
=> "Hamza"
irb(main):017:0> a.children.first.name
Template Load (1.9ms) SELECT "templates".* FROM "templates" INNER JOIN "related_templates" ON "templates"."id" = "related_templates"."child_id" WHERE "related_templates"."parent_id" = $1 ORDER BY "templates"."id" ASC LIMIT 1 [["parent_id", 158]]
=> "Hamza"
Dont know what is wrong here ?

Both object only exist in memory, when you validate them. The uniqueness validation passes in both cases, because the validation checks if there is a similar record in the database already.
Have a look at the logs:
# you call save
irb(main):007:0> a.save
(0.9ms) SAVEPOINT active_record_1
# Rails validates the first object
Template Exists (1.3ms) SELECT 1 AS one FROM "templates" WHERE LOWER("templates"."name") = LOWER('Hamza') LIMIT 1
Container Load (0.7ms) SELECT "containers".* FROM "containers" WHERE "containers"."id" = $1 LIMIT 1 [["id", 2]]
# Rails validates the second object
Template Exists (0.5ms) SELECT 1 AS one FROM "templates" WHERE LOWER("templates"."name") = LOWER('Hamza') LIMIT 1
Container Load (0.2ms) SELECT "containers".* FROM "containers" WHERE "containers"."id" = $1 LIMIT 1 [["id", 2]]
# At this point Rails thinks that both records will be fine, because the validation passed
# Rails saved the first object
SQL (0.3ms) INSERT INTO "templates" ("something_id", "name", "another_something_id", "container_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["something_id", 1], ["name", "Hamza"], ["another_something_id", 16], ["container_id", 2]]
# Rails saved the second object
SQL (0.2ms) INSERT INTO "templates" ("name", "another_something_id", "container_id") VALUES ($1, $2, $3) RETURNING "id" [["name", "Hamza"], ["another_something_id", 16], ["container_id", 2]]
This is good example why Rails uniqueness validations are not 100% secure. Another example might be race conditions, when multiple requests hit the application at the same time.
The only way to avoid this kind of problems, is to add a unique index to the database table.

Related

Include Active Storage attachments in Active Record query

Using Rails 5.2 and Active Storage, I set up an Item class with some images:
class Item < ApplicationRecord
has_many_attached :images
end
I'd like to use ActiveRecord::QueryMethods.includes to eager-load the images, pretty standard Rails stuff with has_many, but:
Item.includes(:images)
=> ActiveRecord::AssociationNotFoundError ("Association named 'images' was not found on Item; perhaps you misspelled it?")
Item.includes(:attachments)
=> ActiveRecord::AssociationNotFoundError ("Association named 'attachments' was not found on Item; perhaps you misspelled it?")
Item.includes(:active_storage_attachments)
=> ActiveRecord::AssociationNotFoundError ("Association named 'active_storage_attachments' was not found on Item; perhaps you misspelled it?")
Any idea how to make it work?
ActiveStorage provides a method to prevent N+1 queries
Gallery.where(user: Current.user).with_attached_photos
https://api.rubyonrails.org/classes/ActiveStorage/Attached/Model.html#method-i-has_many_attached
So, in your case:
Item.with_attached_images
…aaand I found the answer:
Item.reflections.keys
=> ["location", "images_attachments", "images_blobs", "taggings", "base_tags", "tag_taggings", "tags"]
The name of the Active Storage-generated association is images_attachments even though it is accessible through Item#images. Here's the solution:
Item.includes(:images_attachments)
Item Load (0.6ms) SELECT "items".* FROM "items" LIMIT $1 [["LIMIT", 11]]
ActiveStorage::Attachment Load (0.6ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_type" = $1 AND "active_storage_attachments"."name" = $2 AND "active_storage_attachments"."record_id" IN ($3, $4, $5, $6, $7) [["record_type", "Item"], ["name", "images"], ["record_id", 3], ["record_id", 2], ["record_id", 4], ["record_id", 5], ["record_id", 1]]
=> #<ActiveRecord::Relation […]>

Rails: Issue assocating a record with a user who did not create that record

I have a single Users table with roles defined using enums in user.rb:
enum role: { staff: 0, clinician: 1 }
A staff user can create a patient record. That staff user who creates the patient record may be that patient's staff clinician, or they may not be, in which case I have a dropdown form that gives options for select of all stuff users. (The clinician user role is for outside clinicians - they are not involved)
I have a patients table in which I have user.id, which I intend to use to store the staff user id who created the patient, and staff_clinician_id, which I
intend to use to store the id of the patient's doctor (who will also be a staff user - confusing I know). Here's my patients schema:
create_table "patients", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "age"
t.integer "staff_clinician_id"
t.integer "user_id"
t.index ["staff_clinician_id"], name: "index_patients_on_staff_clinician_id"
t.index ["user_id"], name: "index_patients_on_user_id"
Then in my patients controller I've permitted staff_clinician_id and user_id:
def patient_params
params.require(:patient).permit(:age, :staff_clinician_id, :user_id, insurance_ids: [], gender_ids: [], concern_ids: [], race_ids: [])
end
and in the Patient model I've created this relationship:
has_one :staff_clinician, through: :users
Here is my form:
<%= select_tag "staff_clinician_id", options_from_collection_for_select(User.where(role:"staff"), "id", "name"), prompt: "Select this patient's clinician" %>
When I submit a new patient, the server says:
Started POST "/patients" for ::1 at 2017-09-25 14:16:44 -0400
Processing by PatientsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "patient"=>{"gender_ids"=>["1"], "race_ids"=>["1"], "insurance_ids"=>["1"], "concern_ids"=>["31"], "age"=>"243"}, "staff_clinician_id"=>"5", "commit"=>"Post"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = ? ORDER BY "users"."id" ASC LIMIT ? [["remember_token", "3e607ec61e623710c58c42a0d313395439f82a82"], ["LIMIT", 1]]
Insurance Load (0.2ms) SELECT "insurances".* FROM "insurances" WHERE "insurances"."id" = 1
Gender Load (0.1ms) SELECT "genders".* FROM "genders" WHERE "genders"."id" = 1
Concern Load (0.2ms) SELECT "concerns".* FROM "concerns" WHERE "concerns"."id" = 31
Race Load (0.1ms) SELECT "races".* FROM "races" WHERE "races"."id" = 1
(0.0ms) begin transaction
Gender Exists (0.2ms) SELECT 1 AS one FROM "genders" WHERE "genders"."name" = ? AND ("genders"."id" != ?) LIMIT ? [["name", "Female"], ["id", 1], ["LIMIT", 1]]
Race Exists (0.1ms) SELECT 1 AS one FROM "races" WHERE "races"."name" = ? AND ("races"."id" != ?) LIMIT ? [["name", "American Indian or Alaska Native"], ["id", 1], ["LIMIT", 1]]
SQL (0.3ms) INSERT INTO "patients" ("created_at", "updated_at", "age", "user_id") VALUES (?, ?, ?, ?) [["created_at", 2017-09-25 18:16:44 UTC], ["updated_at", 2017-09-25 18:16:44 UTC], ["age", 243], ["user_id", 21]]
SQL (0.1ms) INSERT INTO "genders_patients" ("gender_id", "patient_id") VALUES (?, ?) [["gender_id", 1], ["patient_id", 7]]
Gender Exists (0.1ms) SELECT 1 AS one FROM "genders" WHERE "genders"."name" = ? AND ("genders"."id" != ?) LIMIT ? [["name", "Female"], ["id", 1], ["LIMIT", 1]]
SQL (0.1ms) INSERT INTO "concerns_patients" ("concern_id", "patient_id") VALUES (?, ?) [["concern_id", 31], ["patient_id", 7]]
SQL (0.1ms) INSERT INTO "insurances_patients" ("insurance_id", "patient_id") VALUES (?, ?) [["insurance_id", 1], ["patient_id", 7]]
SQL (0.2ms) INSERT INTO "patients_races" ("race_id", "patient_id") VALUES (?, ?) [["race_id", 1], ["patient_id", 7]]
Race Exists (0.1ms) SELECT 1 AS one FROM "races" WHERE "races"."name" = ? AND ("races"."id" != ?) LIMIT ? [["name", "American Indian or Alaska Native"], ["id", 1], ["LIMIT", 1]]
(10.5ms) commit transaction
Redirected to http://localhost:3000/referral_requests/new?patient_id=7
Completed 302 Found in 172ms (ActiveRecord: 17.5ms)
but when I do Patient.last in console, it hasn't saved the staff_clinician_id. it is nil
What am I doing wrong? Any help appreciated!
Your select tag should be named patient[staff_clinician_id], not staff_clinician_id.
<%= select_tag "patient[staff_clinician_id]", options_from_collection_for_select(User.where(role:"staff"), "id", "name"), prompt: "Select this patient's clinician" %>
If you use the object-based form builder, you can use the shorthand:
<% form_for #patient do |f| %>
...
<%= f.select :staff_clinician_id ... %>
...
<% end %>
select and select_tag are used in very different contexts.

ActiveRecord has_many relationships forget changes to children?

I have an instance of type A that has_many Bs. When the A.foo = value method gets called, I actually want to write a method that delegates to that foo= call the first of the A's Bs.
class A < ActiveRecord::Base
has_many :bs, autosave: true
def foo
bs.first.foo
end
def foo=(val)
bs.first.foo = val
end
end
class B < ActiveRecord::Base
belongs_to A
end
rails generate model A
rails generate model B a:references foo:string
2.3.0 :001 > a = A.create!
(0.1ms) begin transaction
SQL (0.3ms) INSERT INTO "as" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2016-10-08 18:03:18.255107"], ["updated_at", "2016-10-08 18:03:18.255107"]]
(7.8ms) commit transaction
=> #<A id: 1, created_at: "2016-10-08 18:03:18", updated_at: "2016-10-08 18:03:18">
Create an A and call it a.
2.3.0 :002 > b = B.create!(a: a, foo: "initial")
(0.4ms) begin transaction
SQL (0.4ms) INSERT INTO "bs" ("a_id", "foo", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["a_id", 1], ["foo", "initial"], ["created_at", "2016-10-08 18:03:40.658035"], ["updated_at", "2016-10-08 18:03:40.658035"]]
(8.3ms) commit transaction
=> #<B id: 1, a_id: 1, foo: "initial", created_at: "2016-10-08 18:03:40", updated_at: "2016-10-08 18:03:40">
Create a B and call it b. Make it a child of A. Set it's foo property to "initial".
2.3.0 :003 > a.reload.foo
A Load (0.2ms) SELECT "as".* FROM "as" WHERE "as"."id" = ? LIMIT 1 [["id", 1]]
B Load (0.2ms) SELECT "bs".* FROM "bs" WHERE "bs"."a_id" = ? ORDER BY "bs"."id" ASC LIMIT 1 [["a_id", 1]]
=> "initial"
Check that a sees it's new child's foo: yes. As expected.
2.3.0 :004 > a.foo = "set"
B Load (0.1ms) SELECT "bs".* FROM "bs" WHERE "bs"."a_id" = ? ORDER BY "bs"."id" ASC LIMIT 1 [["a_id", 1]]
=> "set"
2.3.0 :005 > a.foo
B Load (0.4ms) SELECT "bs".* FROM "bs" WHERE "bs"."a_id" = ? ORDER BY "bs"."id" ASC LIMIT 1 [["a_id", 1]]
=> "initial"
Whaaat? I just called a.foo = "set". Now when I call a.foo again to read the value back, I get "initial"? That's not the way it works for has_one relationships. Why is ActiveRecord reloading from the DB every time, instead of caching it's queries?
Ultimately, my intention is to call a.save!, and have it autosave down to the b. But that's not possible if the relationship gets amnesia about every pending change. What's going on here?!
Set up a has_one relationship between A and B and delegate :foo to the has_one association.
class A
has_many :bs
has_one :first_b, -> { first },
class_name: 'B'
delegate :foo, to: :first_b
end
To avoid the query for B you can use .joins, includes or eager_load.

rspec model test failing

I am writing an app to help me keep track of my social media advertising budgets. When you enter a new advert it should calculate and update the amount spent on the budget it is drawing from. Here is my model that achieves that.
class Advert < ActiveRecord::Base
belongs_to :budget
before_save :update_budget
after_destroy :update_budget
validates :budget_id, :name, :platform, :ad_type, :amount, :start_date, :end_date, presence: true
validates :amount, numericality: true
validate :check_budget
# Checks to see if there is enough budget remaining to set up advert
def check_budget
if self.amount > self.budget.amount_remaining
errors.add(:amount, " cannot exceed amount remaining in budget.")
end
end
# Updates the amount remaining in the budget on advert save.
def update_budget
budget = Budget.find(self.budget_id)
#adverts = Advert.all
total_spent = self.amount
#adverts.each do |advert|
if advert.budget_id == self.budget_id
total_spent += advert.amount
end
end
budget.amount_spent = total_spent
budget.save
end
end
This all works but I am currently teaching myself to write tests so I thought I would write a test in rspec for it.
require 'rails_helper'
describe Advert do
it "updates budget before save" do
advert = create(:advert)
budget = advert.budget
expect(budget.amount_spent).to eq(advert.amount)
expect(budget.amount_remaining).to eq(budget.amount - budget.amount_spent)
end
end
However, this test if failing but I cannot figure out why. Here is the error code.
1) Advert updates budget before save
Failure/Error: expect(budget.amount_spent).to eq(advert.amount)
expected: 7.0 (#<BigDecimal:7ffa61358b18,'0.7E1',9(18)>)
got: 0.0 (#<BigDecimal:7ffa6026a9a0,'0.0',9(18)>)
(compared using ==)
# ./spec/models/advert_spec.rb:27:in `block (2 levels) in <top (required)>'
And here is the relevant test log.
SQL (0.3ms) INSERT INTO "budgets" ("name", "amount", "client_id", "amount_remaining", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["name", "eos"], ["amount", "432.0"], ["client_id", 102], ["amount_remaining", "432.0"], ["created_at", "2016-03-12 18:08:54.607999"], ["updated_at", "2016-03-12 18:08:54.607999"]]
(0.1ms) RELEASE SAVEPOINT active_record_1
(0.2ms) SAVEPOINT active_record_1
Budget Load (0.4ms) SELECT "budgets".* FROM "budgets" WHERE "budgets"."id" = $1 LIMIT 1 [["id", 49]]
Advert Load (0.5ms) SELECT "adverts".* FROM "adverts"
SQL (0.4ms) UPDATE "budgets" SET "amount_spent" = $1, "amount_remaining" = $2, "updated_at" = $3 WHERE "budgets"."id" = $4 [["amount_spent", "7.0"], ["amount_remaining", "425.0"], ["updated_at", "2016-03-12 18:08:54.616491"], ["id", 49]]
SQL (0.4ms) INSERT INTO "adverts" ("budget_id", "name", "platform", "ad_type", "amount", "start_date", "end_date", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id" [["budget_id", 49], ["name", "ut"], ["platform", "voluptate"], ["ad_type", "facere"], ["amount", "7.0"], ["start_date", "2016-03-01"], ["end_date", "2016-04-12"], ["created_at", "2016-03-12 18:08:54.619698"], ["updated_at", "2016-03-12 18:08:54.619698"]]
(0.2ms) RELEASE SAVEPOINT active_record_1
(0.2ms) ROLLBACK
Interestingly if I comment out the first 'expect' the test passes. It's as though it cannot access advert.amount so set's it as 0.
Anyone have any ideas?
This solved my issue.
describe Advert do
it "updates budget before save" do
advert = build(:advert)
budget = advert.budget
expect(budget.amount_spent).to eq(0)
advert.save
budget.reload
expect(budget.amount_spent).to eq(advert.amount)
expect(budget.amount_remaining).to eq(budget.amount - budget.amount_spent)
end
I think the source of my problem was not reloading my budget which meant that I was trying to access the attribute before it had been updated.

Rails nested attributes not being updated

I'm building my first Rails app and one of the important features in it is having users who speak and/or want to learn languages. In the user edit profile page, I allow him/her to choose what languages he/she speaks and/or wants to learn from a list (I'm using ryanb's nested_form gem):
There are 3 models involved in this: User, Speaks, Language
The languages table is just a table with languages of the world, it doesn't change. It consists basically of ISO codes for languages and their names. I populate it by running a script that reads from the official file I downloaded. Still I was simply using Rails defaults, so the table had an id column, and it was all working fine.
Then I decided to make a change and remove the id column, because it didn't make any sense anyway. I want my app to be up to date with the ISO list. I want the ISO code to identify the languages, not a meaningless id. I want to use
user.speaks.create!(language_id: "pt", level: 6)
instead of
user.speaks.create!(language_id: 129, level: 6)
I know it's unlikely that the ISO list will change but, if it does, I want to simply run my script again with the new file and not worry if the id column will still match the same ISO code as before. So I made the change. Now I can use user.speaks.create the way I want and the association works perfectly in the console. The problem is my form simply isn't working anymore. The data is sent but I don't understand the logs. They show a bunch of SELECTS but no INSERTS or UPDATES, I don't get why. Does anybody have any idea?
Here are my models:
class User < ActiveRecord::Base
attr_accessible ..., :speaks, :speaks_attributes, :wants_to_learn_attributes
has_many :speaks, :class_name => "Speaks", :dependent => :destroy
has_many :speaks_languages, :through => :speaks, :source => :language #, :primary_key => "iso_639_1_code"
has_many :wants_to_learn, :class_name => "WantsToLearn", :dependent => :destroy
has_many :wants_to_learn_languages, :through => :wants_to_learn, :source => :language #, :primary_key => "iso_639_1_code"
...
accepts_nested_attributes_for :speaks #, :reject_if => :speaks_duplicate, :allow_destroy => true
accepts_nested_attributes_for :wants_to_learn #, :reject_if => :wants_to_learn_duplicate, :allow_destroy => true
# EDIT 1: I remembered these pieces of code silenced errors, so I commented them out
...
end
class Speaks < ActiveRecord::Base
self.table_name = "speak"
attr_accessible :language, :language_id, :level
belongs_to :user
belongs_to :language
validates :user, :language, :level, presence: true
...
end
#EDIT 4:
class WantsToLearn < ActiveRecord::Base
self.table_name = "want_to_learn"
attr_accessible :language, :language_id
belongs_to :user
belongs_to :language
validates :user, :language, presence: true
...
end
class Language < ActiveRecord::Base
attr_accessible :iso_639_1_code, :name_en, :name_fr, :name_pt
has_many :speak, :class_name => "Speaks"
has_many :users_who_speak, :through => :speak, :source => :user
has_many :want_to_learn, :class_name => "WantsToLearn"
has_many :users_who_want_to_learn, :through => :want_to_learn, :source => :user
end
Controller:
def update
logger.debug params
if #user.update_attributes(params[:user])
#user.save
flash[:success] = "Profile updated"
sign_in #user
redirect_to :action => :edit
else
render :action => :edit
end
end
View:
<%= nested_form_for(#user, :html => { :class => "edit-profile-form"} ) do |f| %>
<%= render 'shared/error_messages' %>
<table border="0">
<tr><td colspan="2"><h2 id="languages" class="bblabla">Languages</h2></td></tr>
<tr>
<td><span>Languages you speak</span></td>
<td class="languages-cell">
<div id="speaks">
<%= f.fields_for :speaks, :wrapper => false do |speaks| %>
<div class="fields">
<%= speaks.select(:language_id,
Language.all.collect {|lang| [lang.name_en, lang.id]},
{ :selected => speaks.object.language_id, :include_blank => false },
:class => 'language') %>
<%= speaks.label :level, "Level: " %>
<%= speaks.select(:level, Speaks.level_options, { :selected => speaks.object.level }, :class => 'level') %>
<%= speaks.link_to_remove raw("<i class='icon-remove icon-2x'></i>"), :class => "remove-language" %>
</div>
<% end %>
</div>
<p class="add-language"><%= f.link_to_add "Add language", :speaks, :data => { :target => "#speaks" } %></p>
</td>
</tr>
...
Log:
Started PUT "/users/1" for 127.0.0.1 at 2013-07-19 08:41:16 -0300
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZmaU9...", "user"=>{"speaks_attributes"=>{"0"=>{"language_id"=>"pt", "level"=>"6", "_destroy"=>"false"}, "1374234067848"=>{"language_id"=>"en", "level"=>"5", "_destroy"=>"false"}}, "wants_to_learn_attributes"=>{"0"=>{"language_id"=>"ro", "_destroy"=>"false", "id"=>"1"}}, "home_location_attributes"=>{"google_id"=>"7789d9...", "latitude"=>"-22.9035393", "longitude"=>"-43.20958689999998", "city"=>"Rio de Janeiro", "neighborhood"=>"", "administrative_area_level_1"=>"Rio de Janeiro", "administrative_area_level_2"=>"", "country_id"=>"BR", "id"=>"1"}, "gender"=>"2", "relationship_status"=>"2", "about_me"=>""}, "commit"=>"Save changes", "id"=>"1"}
[1m[35mUser Load (0.3ms)[0m SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'bjdvI...' LIMIT 1
[1m[36mUser Load (0.2ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1[0m [["id", "1"]]
{"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"ZmaU9W...", "user"=>{"speaks_attributes"=>{"0"=>{"language_id"=>"pt", "level"=>"6", "_destroy"=>"false"}, "1374234067848"=>{"language_id"=>"en", "level"=>"5", "_destroy"=>"false"}}, "wants_to_learn_attributes"=>{"0"=>{"language_id"=>"ro", "_destroy"=>"false", "id"=>"1"}}, "home_location_attributes"=>{"google_id"=>"7789d9...", "latitude"=>"-22.9035393", "longitude"=>"-43.20958689999998", "city"=>"Rio de Janeiro", "neighborhood"=>"", "administrative_area_level_1"=>"Rio de Janeiro", "administrative_area_level_2"=>"", "country_id"=>"BR", "id"=>"1"}, "gender"=>"2", "relationship_status"=>"2", "about_me"=>""}, "commit"=>"Save changes", "action"=>"update", "controller"=>"users", "id"=>"1"}
[1m[35m (0.1ms)[0m BEGIN
[1m[36mWantsToLearn Load (0.2ms)[0m [1mSELECT "want_to_learn".* FROM "want_to_learn" WHERE "want_to_learn"."user_id" = 1 AND "want_to_learn"."id" IN (1)[0m
[1m[35mLocation Load (0.3ms)[0m SELECT "locations".* FROM "locations" WHERE "locations"."google_id" = '7789d...' AND "locations"."latitude" = '-22.9035393' AND "locations"."longitude" = '-43.20958689999998' AND "locations"."city" = 'Rio de Janeiro' AND "locations"."neighborhood" = '' AND "locations"."administrative_area_level_1" = 'Rio de Janeiro' AND "locations"."administrative_area_level_2" = '' AND "locations"."country_id" = 'BR' LIMIT 1
[1m[36mUser Exists (40.0ms)[0m [1mSELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('ariel#pontes.com') AND "users"."id" != 1) LIMIT 1[0m
[1m[35m (96.7ms)[0m UPDATE "users" SET "remember_token" = 'd0pb...', "updated_at" = '2013-07-19 11:41:16.808422' WHERE "users"."id" = 1
[1m[36m (28.7ms)[0m [1mCOMMIT[0m
[1m[35m (0.1ms)[0m BEGIN
[1m[36mUser Exists (0.3ms)[0m [1mSELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('ariel#pontes.com') AND "users"."id" != 1) LIMIT 1[0m
[1m[35m (0.3ms)[0m UPDATE "users" SET "remember_token" = 'gKlW...', "updated_at" = '2013-07-19 11:41:17.072654' WHERE "users"."id" = 1
[1m[36m (0.4ms)[0m [1mCOMMIT[0m
Rendered shared/_error_messages.html.erb (0.0ms)
[1m[35mSpeaks Load (0.3ms)[0m SELECT "speak".* FROM "speak" WHERE "speak"."user_id" = 1
[1m[36mWantsToLearn Load (0.2ms)[0m [1mSELECT "want_to_learn".* FROM "want_to_learn" WHERE "want_to_learn"."user_id" = 1[0m
[1m[35mLanguage Load (0.3ms)[0m SELECT "languages".* FROM "languages"
[1m[36mCountry Load (0.3ms)[0m [1mSELECT "countries".* FROM "countries" WHERE "countries"."iso_3166_code" = 'BR' LIMIT 1[0m
[1m[35mCACHE (0.0ms)[0m SELECT "languages".* FROM "languages"
[1m[36mCACHE (0.0ms)[0m [1mSELECT "languages".* FROM "languages" [0m
Rendered users/edit.html.erb within layouts/application (39.8ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_header.html.erb (1.1ms)
Rendered layouts/_footer.html.erb (0.2ms)
Completed 200 OK in 576ms (Views: 160.7ms | ActiveRecord: 168.7ms)
Hope someone has an insight cause I've been looking all over the internet for the past 2 days with no luck. Thanks in advance!
EDIT 1
I placed the accepts_nested_attributes_for lines after the associations were made, as suggested by ovatsug25, but it didn't seem to make any change. I remembered, however, that there were some options in the User model that silenced errors, which of course hinders the debugging, so I commented these options out. Now I have the following error:
PG::Error: ERROR: operator does not exist: character varying = integer
LINE 1: ...M "languages" WHERE "languages"."iso_639_1_code" = 0 LIMIT ...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "languages".* FROM "languages" WHERE "languages"."iso_639_1_code" = 0 LIMIT 1
I have NO IDEA why Rails is trying to select a language with pk = 0. Even if the pk WAS an integer this wouldn't make sense (would it???) since the default id starts from 1. And even if it started from zero, why would it be trying to select it anyway? Where is this zero comming from?? And I can't "add explicit type casts". The pk is a string and will never be 0 or '0' for that matter. This query doesn't make sense and simply isn't supposed to happen!
EDIT 2
I tried to update the attributes in the console and got the following:
irb(main):006:0> ariel = User.find(1)
User Load (101.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
=> #<User id: 1, first_name: "Ariel", last_name: "Pontes", ...>
irb(main):007:0> params = {"user"=>{"speaks_attributes"=>{"0"=>{"language_id"=>"pt", "level"=>"6", "_destroy"=>"false"}, "1374444891951"=>{"language_id"=>"en", "l
evel"=>"5", "_destroy"=>"false"}}, "wants_to_learn_attributes"=>{"0"=>{"language_id"=>"ro", "_destroy"=>"false"}}, "home_location_attributes"=>{"google_id"=>"778...c5a", "latitude"=>"-22.9035393", "longitude"=>"-43.20958689999998", "city"=>"Rio de Janeiro", "neighborhood"=>"", "administrative
_area_level_1"=>"Rio de Janeiro", "administrative_area_level_2"=>"", "country_id"=>"BR", "id"=>"1"}, "gender"=>"2", "relationship_status"=>"2", "about_me"=>""}}
=> {"user"=>{"speaks_attributes"=>{"0"=>{"language_id"=>"pt", "level"=>"6", "_destroy"=>"false"}, "1374444891951"=>{"language_id"=>"en", "level"=>"5", "_destroy"=
>"false"}}, "wants_to_learn_attributes"=>{"0"=>{"language_id"=>"ro", "_destroy"=>"false"}}, "home_location_attributes"=>{"google_id"=>"778...c5a", "latitude"=>"-22.9035393", "longitude"=>"-43.20958689999998", "city"=>"Rio de Janeiro", "neighborhood"=>"", "administrative_area_level_1"=>"Rio de
Janeiro", "administrative_area_level_2"=>"", "country_id"=>"BR", "id"=>"1"}, "gender"=>"2", "relationship_status"=>"2", "about_me"=>""}}
irb(main):008:0> ariel.update_attributes(params[:user])
(0.1ms) BEGIN
User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('ariel#pontes.com') AND "users"."id" != 1) LIMIT 1
(24.9ms) UPDATE "users" SET "remember_token" = '0tv...Cw', "updated_at" = '2013-07-22 15:45:30.705217' WHERE "users"."id" = 1
(54.3ms) COMMIT
=> true
irb(main):009:0>
Basically, it only updates the remember_token and updated_at for some reason.
EDIT 3
I tried to update only the spoken languages and it worked:
irb(main):012:0> ariel.update_attributes({"speaks_attributes"=>{"0"=>{"language_id"=>"pt", "level"=>"6", "_destroy"=>"false"}, "1374444891951"=>{"language_id"=>"e
n", "level"=>"5", "_destroy"=>"false"}}})
(0.2ms) BEGIN
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Language Load (0.8ms) SELECT "languages".* FROM "languages" WHERE "languages"."iso_639_1_code" = 'pt' LIMIT 1
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Language Load (0.2ms) SELECT "languages".* FROM "languages" WHERE "languages"."iso_639_1_code" = 'en' LIMIT 1
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('ariel#pontes.com') AND "users"."id" != 1) LIMIT 1
(0.2ms) UPDATE "users" SET "remember_token" = 'MYh5X1XoF6OsVIo3rhDNzQ', "updated_at" = '2013-07-22 22:05:08.198025' WHERE "users"."id" = 1
SQL (42.9ms) INSERT INTO "speak" ("created_at", "language_id", "level", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["created_at", Mo
n, 22 Jul 2013 22:05:08 UTC +00:00], ["language_id", "pt"], ["level", 6], ["updated_at", Mon, 22 Jul 2013 22:05:08 UTC +00:00], ["user_id", 1]]
SQL (0.4ms) INSERT INTO "speak" ("created_at", "language_id", "level", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["created_at", Mon
, 22 Jul 2013 22:05:08 UTC +00:00], ["language_id", "en"], ["level", 5], ["updated_at", Mon, 22 Jul 2013 22:05:08 UTC +00:00], ["user_id", 1]]
(14.7ms) COMMIT
=> true
I'm starting to fear it may be a case of witchcraft.
PS: Does anybody know why it loads the User 3 times? Seems rather pointless and wasteful.
The biggest clue is this error that caught your eye:
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "languages".* FROM "languages" WHERE "languages"."iso_639_1_code" = 0 LIMIT 1
If you're providing a string value for a model attribute, but the underlying database column is a numeric column, Rails will try to convert the string value to the appropriate numeric type. So, if the underlying column is of type integer, the string input will be interpreted as an integer, using String#to_i. If the string doesn't start with a number, it will be converted to 0.
The Rails console (rails c) can be a useful tool for debugging issues like this. In this case, on the console, you can run WantsToLearn.columns_hash['language_id'].type to see what type Rails thinks it should be using for that attribute. Of course, you can also just as easily check the migrations.
I used to have a problem like this and solved it by segreating the accepts_attributes_for calls to the very bottom after all associations and accessible attributes have been declared. (I also merged attr_accesible into one call. I think ryanb says something in this video about the order of the calls. http://railscasts.com/episodes/196-nested-model-form-revised?view=asciicast.
Makes sense? No. But it worked for me.

Resources