ruby on rails - Faking a Database record for Active Record methods -


i'm using find_by on association:

"sub" has many 1 relation "main"

@main.subs.find_by(x: 123) 

in cases want access , retrieve database "sub" record related "main", using regular select:

select subs.* subs subs.main_id = 333 , subs.x = 123 

but there's scenario, in want ignore database , access stub i've created of "subs" under "main":

stub_sub = sub.new(id: 22, x: 123, main_id: 333) @main.subs << stub_sub 

@main isn't saved in database either , created sub:

@main = main.new(id: 333) 

when find_by line while debugging, , try , access @main.subs, looks active record relation i'd db query, if find_by/all try access db , see there's nothing there , return empty relation.

is there way prevent find_by (or active record method) accessing database , work on stub relation i've created it?

i think there few misunderstandings in question there. firstly, find_by method not return all matching records just first one, wanted use where method instead.

secondly, << operator on has_many association saves association record a where query should return after assigning association, i.e. after calling <<.

update: if main object not yet exist in database either, indeed << operator not save anything. in case, solution comes mind give activerecord methods (such find_by or where) because try query db information , search matching associated record manually instead.

so instead of @main.subs.where(x: 123) do:

@main.subs.to_a.select { |sub| sub.x == 123 } 

this way, load attached associations first, including newly attached , unsaved ones , filter them using ruby condition against attributes.

the big disadvantage of when using code saved record, load all associated records, not match condition. thus, if had record lot of associated records, you'd killing performance of such filtering.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -