Rails在查询中选择别名

时间:2011-12-06 18:09:34

标签: ruby-on-rails-3.1

所以我有2个表actor和actor2role。后者是一个查找(联结)表,用于关联actor,role和dvd。我需要创建一个带别名的查询,所以我有这个方法:

def self.remove_duplicate_by_id(id)
    offendingActor = self.find(id).actor # get the actor's name
    ids = self.find_by_sql("SELECT MIN(id) AS minId, MAX(id) AS maxId, actor FROM `dvd_actor` WHERE actor = '#{offendingActor}'")
    rolesForOffender = ids.actor2role # throws error
end

问题是ids不是ActiveRecord对象所以我不能使用actor2role方法(这是我在Rails中的2个表之间建立的关系,当你做类似于Actor.first.actor2role

所以问题是:我是否注定要手动执行此操作,然后发出另一个sql查询来重新创建actor2role方法将完成的内容,或者是否有某种方法可以使用Rails对象执行此操作?

我真的很想在可能的情况下本地完成,因为我还必须发出这些查询:

UPDATE dvd_actor2role SET actorid = $d->minId WHERE actorId = $d->maxId");
DELETE FROM dvd_actor2role WHERE actorId = $d->maxId LIMIT 1");

这甚至可能吗?

1 个答案:

答案 0 :(得分:0)

最后,我选择了这个似乎可以解决问题的方法。如果任何人都可以发现任何可以优化的代码,或者某些内在错误的代码(并且感觉像是在喋喋不休),请随时发表评论。

actorObject = self.find_by_id(id) # get the object because we need it below for other queries
    offendingActor = actorObject.actor
    ids = self.select("MIN(id) AS minId, MAX(id) AS maxId, id, actor").find_by_actor(offendingActor)
    rolesForOffender = actorObject.actor2role
    rolesForOffender.each do |r|
        # first find out if the relationship already exists or we get a SQL error for the foreign key relationship.
        exists = Actor2role.where("actorId = ? AND roleId = ?", ids.minId, r.roleId)
        if exists.nil?
            Actor2role.update_all("actorId = #{ids.minId}, actorId = #{ids.maxId}")         
        end
    end
    self.destroy(ids.maxId) # delete this guy in actor table
end