Ruby on rails 3.1 Rails在查询中选择别名

Ruby on rails 3.1 Rails在查询中选择别名,ruby-on-rails-3.1,Ruby On Rails 3.1,所以我有两张表,分别是演员和演员角色。后者是一个查找(连接)表,用于关联参与者、角色和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 FR

所以我有两张表,分别是演员和演员角色。后者是一个查找(连接)表,用于关联参与者、角色和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中的两个表之间建立的关系,当您执行类似于
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");

这有可能吗?

最后,我选择了这一点,这似乎起到了作用。如果有人能发现任何可以优化的代码,或者某些固有的错误(感觉像是插话),请随时发表评论

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