开发者

Rails find method :select alias as id?

I currently have a .find method in one of my rails controller actions - the relevant part is:

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

I am getting some odd beha开发者_开发百科viour trying to alias the last_name column as id - if I alias it as anything else, it works fine (i can do last_name as xyz and it outputs the last name in a column called xyz, but as I am using this to populate a drop-down where I need to have the name in the id column, i need it to be called 'id').

I should point out that it does output an id column, but it is always "id":0.

Could anyone shed any light on what I need to do to get this column aliased as 'id'?

Thanks!


I'm not sure of how you can do this in a Rails query statement. Rails is going to try and take over the id column, casting the value returned by the database as id with the type of column that id is (presumably integer). That's why your id column keeps getting set to 0, because "string".to_i #=> 0

However, there is a way to do it, once you have the results back.

Since you have the question tagged as Rails 3, it is preferable to use the new ActiveRelation syntax. You can do the following:

# 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

That will get you a hash with the id value as the text string value last_name and a name value as the same.

Hope that helps!


You shouldn't need to setup aliases in the finder SQL just to populate a drop-down. Instead simply use the last_name value for the value attribute (as well as the display text).

Eg if you're using the collection_select helper:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜