Squeel evaluating a string as a keypath for joins

两盒软妹~` 提交于 2019-12-11 01:31:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!