开发者

rails 3; activerecord; where; NOT EQUAL condition comparison between two columns in database

Is there some way of comparing two columns in a database using where?

Say, I have two columns for user that tells:

  1. city_of_birth
  2. favourite_city

And I would like a list of users that have favourite_city that is different from city_of_birth.

I was hoping somethin开发者_StackOverflowg like this would work.

@users = User.where(
  :city_of_birth != :favourite_city
).all

Running this results in

undefined method `where' for nil:NilClass

There are similar questions asked about using conditional statements for where, but none of them were about conditional statements about the columns in database itself.

Thank you in advance for the help.


The error relates to the constant User not being defined, however to answer your question about the where method...

:city_of_birth != :favourite_city

This will always be true, so your actually calling where like this...

User.where(true)

This won't do much I'm afraid. I think you maybe getting this confused with the hash condition syntax which can be used. That also won't be of much use to you. You would need to use a string condition like this...

User.where('users.city_of_birth != users. favourite_city')

This is effectively just a snippet of SQL that will eventually be included in the final statement sent to the database.


This error is stating that User isn't defined -- either you have the wrong class name, or it's not being loaded into your environment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜