Ruby: Use string interpolation to access ActiveRecord properties -
is possible me use string interpolation build activerecord query so:
query = '.owner.name' widget = widget.first name = "#{widget" + query + "}"
this doesn't work, i'm looking acceptable alternative.
query = '.owner.name' widget = widget.first name = eval "widget#{query}"
not idea, work.
with great power comes great responsibility (and risk).
since rails uses hashes map columns methods, , hashes "hashes indifferent access" can use either string or symbol. thus:
widget = widget.first widget[:owner] # => returns same widget.owner widget['owner'] # => returns widget.owner.
the problem above code, owner foreign key column, method name actually:
widget['owner_id']
which returns integer rails uses id in owners table. if stringing columns return columns in widget table, can use above code. when stringing query methods because looking relationship in db , calling column method on that.
thus need sort of recursive loop take:
query = 'owner.name' q = query.split'.'
and work results in:
q0 = "#{q[0]}_id" q1 = "#{q[1]}" owner.find(widget[q0])[q1] #owner load (0.6ms) select "owners".* "owners" "owners"."id" = $1 limit 1 [["id", 9]] #=> "joe"
so in theory split query string on dots, add "_id" except last one, chain using (potentially nested) .find
commands. can done? probably. should done way described? not.
if give more descriptive use case scenario people might able offer better answer. trying in broader picture? there might other approach negates need doing asking.
Comments
Post a Comment