问题
While running development code through Heroku console in sandbox mode, I use first_or_create to test for existence of a record:
Right.where(:language => language ).
where(:work_id => work_id ).
where(:contact_id => contact_id ).
first_or_create!
The query to test for existence of the record gets an extra predicate (1=2) added to it, so the record is not found.
SELECT "rights".* FROM "rights" WHERE "rights"."language" = 'ger' AND "rights"."work_id" = 625 AND "rights"."contact_id" = 1435 AND (1 = 2) LIMIT 1
Can anyone suggest how I track down the source of this -- is it a sandbox mode thing, perhaps?
Edit: Sandbox mode being invoked by:
heroku run console -s --app my-app-name
Running Rails console on heroku, in sandbox mode
回答1:
OK, mystery solved.
The first_or_create was being invoked from a method into which arguments were passed for a number of attributes. Something like:
def get_right(language,work_id,contact_id,terms)
right = Right.where(:language => language ).
where(:work_id => work_id ).
where(:terms => terms ).
where(:contact_id => contact_id ).
first_or_create!
right.id
end
When the method was called the terms argument was being passed as {} instead of nil.
Apparently activerecord's method of dealing with stupidity like that is to remove the predicate on the offending column (terms) in the query and append a (1 = 2) predicate instead.
I can't say that I wouldn't rather encounter an error :(
来源:https://stackoverflow.com/questions/16937390/rails-first-or-create-adds-1-2-to-query