2017-01-03 5 views
0

activerecordとpostgresqlが新しく、activerecordクエリに関して次のような問題があります。なぜこれが起こっているのか、どのように解決できるのか理解してください。ActiveRecord 'where'クエリがpostgresqlの特定の文字列に対して機能しない

私は、スキーマファイルで標準的な方法で宣言されている複数のテキスト列を持っています。

create_table "time_entries", force: :cascade do |t| 
    t.string "user" 
    t.string "email"  
    etc .... 
end 

私は 'user' = 'Test'でレコードを検索しようとしています。

TimeEntry.where(user: "Test") 

しかし

TimeEntry.where("user = 'Test'") 

が動作しない、正常に動作します。

2つのクエリが異なるSQLクエリを生成することがわかりましたが、私は 'email'フィールドではなく 'user'フィールドではなぜ動作するのか理解しようとしています。

ユーザー場問合せ:

irb(main):011:0> TimeEntry.where(user: "Test") 
    TimeEntry Load (0.5ms) SELECT "time_entries".* FROM "time_entries" WHERE "time_entries"."user" = $1 [["user", "Test"]] 
=> #<ActiveRecord::Relation [#<TimeEntry id: 1, user: "Test", email: "[email protected]", task: nil, description: "TEST CRM", billable: "No", start_date: "2016-01-03", start_time: "2000-01-01 14:20:22", end_date: "2016-01-03", end_time: "2000-01-01 14:26:29", duration: "2000-01-01 00:06:07", tags: nil, amount: 111, created_at: "2017-01-03 15:39:51", updated_at: "2017-01-03 15:39:51", project_id: 1, resource_id: nil>]> 

irb(main):012:0> TimeEntry.where("user = 'Test'") 
    TimeEntry Load (0.4ms) SELECT "time_entries".* FROM "time_entries" WHERE (user = 'Test') 
=> #<ActiveRecord::Relation []> 
irb(main):013:0> 

メールフィールドクエリ:あなたの助けを

irb(main):013:0> TimeEntry.where(email: "[email protected]") 
    TimeEntry Load (0.3ms) SELECT "time_entries".* FROM "time_entries" WHERE "time_entries"."email" = $1 [["email", "[email protected]"]] 
=> #<ActiveRecord::Relation [#<TimeEntry id: 1, user: "Test", email: "[email protected]", task: nil, description: "TEST CRM", billable: "No", start_date: "2016-01-03", start_time: "2000-01-01 14:20:22", end_date: "2016-01-03", end_time: "2000-01-01 14:26:29", duration: "2000-01-01 00:06:07", tags: nil, amount: 111, created_at: "2017-01-03 15:39:51", updated_at: "2017-01-03 15:39:51", project_id: 1, resource_id: nil>]> 

irb(main):014:0> TimeEntry.where("email = '[email protected]'") 
    TimeEntry Load (0.4ms) SELECT "time_entries".* FROM "time_entries" WHERE (email = '[email protected]') 
=> #<ActiveRecord::Relation [#<TimeEntry id: 1, user: "Test", email: "[email protected]", task: nil, description: "TEST CRM", billable: "No", start_date: "2016-01-03", start_time: "2000-01-01 14:20:22", end_date: "2016-01-03", end_time: "2000-01-01 14:26:29", duration: "2000-01-01 00:06:07", tags: nil, amount: 111, created_at: "2017-01-03 15:39:51", updated_at: "2017-01-03 15:39:51", project_id: 1, resource_id: nil>]> 

感謝。

+1

は、 'ユーザー' のキーワードのようなカラム名ですか? http://stackoverflow.com/questions/7651417/escaping-keyword-like-column-names-in-postgres – Riaan

答えて

1

この問題は、postgresで 'user'が予約されているために発生しているようです。

次のコードは正常に動作します:

TimeEntry.where('time_entries.user = ?', 'Test') 

または

TimeEntry.where('"user" = ?','Test') 
関連する問題