2011-07-01 75 views
1

我现在有一个.find方法在我的rails控制器动作之一 - 相关的部分是:Rails找到方法:选择别名为id?

.find(:all, :select => 'last_name as id, last_name as name') 

我收到一些奇怪的行为试图别名姓氏列ID - 如果我别名它什么否则,它工作正常(我可以做last_name as xyz,它输出名为xyz的列中的姓氏,但因为我使用它来填充下拉列表,我需要在id列中具有名称,所以我需要它被称为'id')。

我应该指出它确实输出了一个id列,但它始终是"id":0

任何人都可以阐明我需要做什么才能获得此列别名为'ID'?

谢谢!

+0

Incase有帮助,正在创建的SQL(不会产生任何错误)是:'SELECT last_name as id,last_name as name FROM“customers”INNER JOIN“dealerships”ON“dealerships”。“id”= “customers”。“dealership_id”WHERE('t'='t')'。 –

回答

2

我不知道如何可以在Rails查询语句做到这一点。 Rails将尝试接管id列,并将数据库返回的值作为idid(可能是整数)列的类型进行比较。这就是为什么你的id列不断设置为0,因为"string".to_i #=> 0

但是,有办法做到这一点,一旦你有结果回来。

由于您的问题标记为Rails 3,因此最好使用新的ActiveRelation语法。你可以做到以下几点:

# First, get the results from the query, then loop through all of them. 
Customer.select("last_name as 'ln', last_name as 'name'").all.collect do |c| 
    # The first step of the loop is to get the attributes into a hash form 
    h = c.attributes 
    # The next step is to create an "id" key in the hash. 
    # The Hash#delete method deletes the key/value pair at the key specified and returns the value. 
    # We'll take that returned value and assign it to the just created "id" key. 
    h["id"] = h.delete("ln") 
    # And we have to call out the hash to ensure that it's the returned value from the collect. 
    h 
end 

,将让你与id值作为文本字符串值last_namename值相同的哈希值。

希望有帮助!

+0

优秀 - 作品很棒,非常感谢! –

1

您不应该需要在查找程序SQL中设置别名才能填充下拉列表。相反,只需使用值属性的last_name值(以及显示文本)。

例如,如果你使用的collection_select帮手:

<%= f.collection_select :attribute_id, @collection, :last_name, :last_name %> 
+0

对不起,我应该更具体 - 上面提到的代码是在我的控制器,它是填充jQuery下拉(链接到其他下拉菜单)。下拉列表由JSON对象填充,并在JSON中填充ID列的隐藏字段 - 在这种情况下,我需要隐藏字段中的值为last_name,以便它可以将该字段传递给下一个字段。 –