To set the stage, I'm using rail开发者_如何学Pythons 3 and I have these tables and relationships:
user has_many lists
list has_many tasks
task has_many stints
I would like to build a query that allows me to select all of the current users stints, and to have the list.id available as an attribute on each stint in the result. I would need to rename list.id to list_id because otherwise it overwrites the id attribute of the stint in the result. I figured "as" would work, but it doesn't.
This gives me the last stint belonging to user 1:
Stint.joins(:task => [{:list => :user }]).where(:lists => {:user_id => 1 }).last
=> #<Stint id: 753, task_id: 245>
What I would like however, is:
=> #<Stint id: 753, task_id: 245, list_id: 2>
So I figured this would work:
Stint.joins(:task => [{:list => :user }]).where(:lists => {:user_id => 1 }).select('stints.*, lists.id as list_id').last
=> #<Stint id: 753, task_id: 245>
As you can see, no difference. But if I don't use "as", I get this:
Stint.joins(:task => [{:list => :user }]).where(:lists => {:user_id => 1 }).select('stints.*, lists.id').last
=> #<Stint id: 2, task_id: 245>
The list.id is used, but because the attribute is set with the name "id" it hides the stint.id.
Any help would be appreciated.
EDIT - The SQL is fine. The query returns the correct columns and values, including list_id.
The problem is that it doesn't create an attribute on the model.The attribute was there all along. It just wasn't being displayed in the result.
s = Stint.joins(:task => [{:list => :user }]).where(:lists => {:user_id => 1 }).select('stints.*, lists.id as list_id').last
=> #<Stint id: 753, task_id: 245>
s.attributes
=> {"id"=>753, "list_id"=>"2", "task_id"=>245}
s.list_id
=> "2"
精彩评论