问题
Here's what I'd really like to do:
Outage.joins{eval "unit.plant"}
I'm going to have a string that represents a squeel keypath. I'd like to send this string into a join statement.
But here's what I get as an error:
#<Class:0x639e328>: unknown class: Squeel::Nodes::Function
I've tried:
Outage.joins{"unit.plant"}
But that does not work... what am I missing?
I don't see any documentation on this on the github page: https://github.com/ernie/squeel/
Thank you for any help!
Update:
I've found a really confusing way to pull this off:
("unit.plant".split ".").map{ |x| x.to_sym }.reverse.inject{ |acc, x| { x => acc } }
This will output:
{:unit=>:plant}
This can be passed into the joins squeel function. I'm sure there has to be a better way than to construct nested symbols :(
回答1:
How about
Outage.joins{Squeel::Nodes::KeyPath.new("unit.plant".split("."))}
Source: KeyPath Docs
回答2:
Alternative solution, it can be chained with outer/inner:
strs = "unit.plant"
Outage.joins{strs.split(".").inject((strs.present? ? self : nil), :__send__)}
# chain with inner
# Outage.joins{strs.split(".").inject((strs.present? ? self : nil), :__send__).inner}
来源:https://stackoverflow.com/questions/11641802/squeel-evaluating-a-string-as-a-keypath-for-joins