How to keep feedback through order, find where, etc.?

Considering the following classes with inverse-has-many-association :

class User < ActiveRecord:Base
  has_many :accounts, inverse_of: :user
end

class Account < ActiveRecord:Base
  belongs_to :user
end

      

And any given User object is loaded like this:

u = User.first
u.some_not_saved_variable = "123"

      

The following code shows that the inverse relationship is not preserved after a new sql statement is executed (the order hits the database):

u.accounts.first.user.some_not_saved_variable                       #=> "123"
u.accounts.order(:created_at).first.user.some_not_saved_variable    #=> nil

      

How can I make sure my custom object still stays the same after ordering, searching where, etc.?

+3


source to share


2 answers


If you want to keep the attribute of the objects but don't want to keep the record, you can try using attributes=(new_attributes)

orassign_attributes(new_attributes, options = {})

In your case:

u = User.first
u.attributes= :some_not_saved_variable => "123"

      



or

u = User.first
u.assign_attributes :some_not_saved_variable => "123"

      

sources: assign_attributes and attributes =

+1


source


I do not think that's possible...

inverse_of

allows you to get a user object without pulling out the database, so the unsaved value some_not_saved_variable

(123) is kept .

However, if you call the order

, find

, where

, and so on, it will be created SQL and stored data will replace the unsaved.

Without inverse_of

:

u.accounts.first.user.some_not_saved_variable
 #SELECT "accounts".* FROM "accounts" WHERE "accounts"."user_id" = 1 LIMIT 1
 #SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
=> "database value" #123 will be lost

      



Usage inverse_of

:

u.accounts.first.user.some_not_saved_variable
 #no SQL statement
=> "123" #123 persist

      

Call order

, find

, where

etc .:

u.accounts.order(:created_at).first.user.some_not_saved_variable 
#SQL to order by created_at

      

This way it will always access the database and the unsaved value will be replaced with the database.

0


source







All Articles