top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Rails: How to remove (and resuse) all existing constraints from ActiveRecord::Relation

+2 votes

I'd like to remove all existing constraints from an ActiveRecord::Relation and leave the rest in-tact.
I am NOT looking for #unscoped since I would like to keep any joins/order clauses around.

Additionally, I would like to re-use the constraints that were removed in another query, so the ability to call #to_sql on them would be a very nice bonus.

This is the best I've been able to hack together:

Order.where(id: 1).where(id: 2).arel.constraints[0].to_sql
 => "`orders`.`id` = 1 AND `orders`.`id` = 2"

...but that just seems wrong. As far as I can tell #constraints always has one item in it, but I don't know that will always be true.

posted Dec 29, 2014 by anonymous

Looking for an answer?  Promote on:
Facebook Share Button Twitter Share Button LinkedIn Share Button

Similar Questions
+1 vote

We recently looked at mongoDB a bit. I was discussing using mongoDB with active record but was told that maybe there are other or better options. Can someone comment on that ?

Also, someone suggested storing a ruby array directly inside of a record where I would have opted for the array to be a separate set of records in active record using has_many and belongs_to .. It seemed to me that how I search on those child records would be a big factor but I soon realized I need to find out what are the options. Do people store arrays and hashes directly in mongo DB fields or is that not the best way to go ?

+2 votes

I am trying to write a simple calendar app and having troubles with time zones. For as many nice Date and Time helpers, action view and active record sure dont play nice with time zones.

I have an appointment model with the appointment_time attribute which is a datetime. My current issue is editing appointment_time with datetime_select within a form tag.

def appt_time
appointment_time.in_time_zone(time_zone) #this is the appointment owners time zone 

This gives a select with the current date and time in UTC, not the appointment date and time. appt_time does get called and returns the correct date and time adjusted for the time zone.

The docs mention nothing about time zones, what is the best way to accomplish this?

+1 vote

Something like x.instance_variables.each.... { |i} .... }

Thought to be a one liner. I can't figure out how to apply strip() to each variable, since instance_variable_get returns the value. I really want something I can apply .strip! to....