Rails Active Record: a build method call should not be stored in the database before a save method call

I have a simple user model

class User < ActiveRecord::Base has_one :user_profile end 

And a simple user_profile model

 class UserProfile < ActiveRecord::Base belongs_to :user end 

The problem is when I call the following build method without calling the save method, I get a new record in the database (if it passes the check)

 class UserProfilesController < ApplicationController def create @current_user = login_from_session @user_profile = current_user.build_user_profile(params[:user_profile]) #@user_profile.save (even with this line commented out, it still save a new db record) redirect_to new_user_profile_path end 

Anyyyyyy has anyyy idea of ​​what's going on.

The definition of this method says the following, but it still saves for me

 build_association(attributes = {}) Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key, but has not yet been saved. 

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one

+4
source share
1 answer

Well, I'm sure experienced veterinarians already know this, but as a rookie I had to figure this long way out ... let me see if I can explain this without stuffing it.

Although I did not save the user_profile object directly, I noticed in my logs that something was updating the last_activity_time user model (and user_profile model) every time I submitted the form (the date of the last user model was also updated when registering, the user also had different things - later I realized that it was installed in the configuration of the Witchcraft gem).

Per http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html AutosaveAssociation is a module that takes care of automatically saving related records when their parent is saved. In my case, user mode is the parent, and the scenario below reflects my experience.

 class Post has_one :author, :autosave => true end post = Post.find(1) post.title # => "The current global position of migrating ducks" post.author.name # => "alloy" post.title = "On the migration of ducks" post.author.name = "Eloy Duran" post.save post.reload post.title # => "On the migration of ducks" post.author.name # => "Eloy Duran" 

The following solutions solved my problem: 1. Stopping Magic (configuring) from updating users last_activity_time (for each action) or 2. Passing the option :: autosave => false when I set the association in the user model as follows

 class User < ActiveRecord::Base has_one :user_profile, :autosave => false end 
+8
source

Source: https://habr.com/ru/post/1380453/


All Articles