简体   繁体   English

活动记录find_by_sql和rspec Expect块。 无故创建新ID

[英]Active Record find_by_sql and rspec expect block. New ids are created for no reason

I am working on a complex SQL query with rails 4.2.1 我正在使用Rails 4.2.1进行复杂的SQL查询

def self.proofreader_for_job(job)
  User.find_by_sql(
    "SELECT * FROM users
     INNER JOIN timers 
     ON users.id = timers.proofreader_id
     INNER JOIN tasks
     ON tasks.id = timers.task_id
     WHERE tasks.job_id = #{job.id}")
end

My schema is (jobs has_many tasks, tasks has_many timers, and a timer belongs_to a user(role: proofreader) through the foriegn key proofreader_id) 我的模式是(作业has_many任务,has_many任务任务,以及一个定时器,通过foriegn键proofreader_id给用户(角色:校对者))

The issue is that when I call the method it is returning what is the correct user's email and attributes but the id doesn't match. 问题是,当我调用该方法时,它返回的是正确的用户的电子邮件和属性,但ID不匹配。

For exeample User.proofreader_for_job(job) returns 例如User.proofreader_for_job(job)返回

[#<User id: 178, email: "testemail@gmail.com">]

testemail@gmail.com is the correct email, but I don't have a user in my db with an id of 178. testemail@gmail.com是正确的电子邮件,但是我的数据库中没有ID为178的用户。

User.all just returns User.all刚刚返回

 [#<User id: 12, email: "fakeemail@gmail.com">,
 #<User id: 11, email: "testemail@gmail.com">]

I noticed the issue in my rspec tests, but it happens on both development and test environments. 我在rspec测试中注意到了这个问题,但是在开发环境和测试环境中都会发生。

Does anyone have any idea why my methods is returning a user with such a high id. 有谁知道我的方法为什么返回具有如此高id的用户? Is this done by design, if so why? 这是设计使然吗,为什么呢?

Thank you. 谢谢。

Since you're doing 'Select *', your statement will return all columns for each of the tables in the JOIN statement. 由于您正在执行“选择*”,因此您的语句将返回JOIN语句中每个表的所有列。 So when you're casting the output from the SQL statement to a User type, I think the wrong 'id' column is being grabbed for the User id (likely the timers or tasks table). 因此,当您将SQL语句的输出强制转换为User类型时,我认为User ID(可能是计时器或任务表)的抓取错误的'id'列。

Try explicitly specifying the columns to return like the below statement: 尝试显式指定要返回的列,如以下语句所示:

User.find_by_sql(
    "SELECT users.id, users.email FROM users
    INNER JOIN timers 
    ON users.id = timers.proofreader_id
    INNER JOIN tasks
    ON tasks.id = timers.task_id
    WHERE tasks.job_id = #{job.id}")
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM