简体   繁体   中英

Is there is any way to write this Rails order query with Ruby symbols instead of strings?

I need to join one table with another prior to ordering records. So far, I've found I can only do the ordering using a string, like so:

customer.joins(:product).order("products.position")

I don't like using hard-coded string values, it feels unsafe. It would be nice if I could use Ruby symbols instead, like below:

customer.joins(:product).order(:products => :position) #doesn't work

How can I do it?

I have a feeling it should be possible, since you can use Ruby symbols when joining a table and doing a where , as demonstrated in the example below:

customer.joins(:product).where(:products => {:manufacturer_id => @manufacturer.id})

No, activerecord was not designed this way. The best reason I can think of is because how would you specify ASC or DESC with that type of naming? You must specify the full statement in a string format for it to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM