named_scope does not show correct columns
-
24-01-2021 - |
Question
Update
I am trying to do is select specific columns and use aliases on them, and use it in a named_scope. I want to use aliases because later on I'll use this as an idea when I try to join many tables, based on the SQL that I have created.
Edit: Im running in Rails 2.3.8 and Ruby 1.8.7
Here is my named_scope...
named_scope :prog_result,:select => "users.id AS 'user_id', users.username AS 'username', users.lastname AS 'lastname', users.firstname AS 'firstname', departments.name AS 'department', versions.number AS 'version'",
:joins => {:department => :version}
And when I try to call it in console User.prog_result
the result is this...
[#<User username: "respondent1", lastname: "res", firstname: "pon">, #<User username: "2222", lastname: "Numero", firstname: "Dos">]
User.prog_result.find(2)
2 is the id of the user "respondent1", the result of User.prog_result.inspect
is this
"[#<User username: \"respondent1\", lastname: \"res\", firstname: \"pon\">, #<User username: \"2222\", lastname: \"Numero\", firstname: \"Dos\">]"
Can someone tell me what am I doing wrong?..
Solution
When you call User.prog_result
in the console, you are really calling User.prog_result.inspect
The console is displays the result by calling #inspect
on the result object.
If instead you called User.prog_result.class
in the console, you'd see that it was an ActiveRecord::NamedScope::Scope
.
If you poke inside these objects that are being returned, you'll probably find what you are expecting.
User.prog_result.first.department => first joined department.name
User.prog_result.last.version => last joined version.number
Both named scopes and passing :joins
, :conditions
and :select
are deprecated in Rails 3.1, so you should probably not be developing new code with them unless you are on Rails 2.3.x. You'll want to do something like this:
User.joins(:department => :version).
select("users.id AS 'user_id', users.username AS 'username', users.lastname AS 'lastname', users.firstname AS 'firstname', departments.name AS 'department', versions.number AS 'version'")
OTHER TIPS
I'm not quit sure about your question, But I assume you are looking at a User object and rails returns an array.
If thats the case, named_scope will always return an array (just like you do a User.find_all())
even if there is only one record
Hope i got your question right ..
thanks and regards
sameera