Rails first_or_create adds (1=2) to query

孤街浪徒 提交于 2019-12-14 01:30:06

问题


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

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