find_by_sql and join

86 views
Skip to first unread message

tanizawa

unread,
Jun 30, 2012, 5:08:32 AM6/30/12
to rubyonra...@googlegroups.com
hi
I amd tanizawa.

I had problem.
I can not get main.name value from below sql.
  "find_by_sql 'select main.id,main.name,sub.name from main left join sub on sub.id = main.id'"
Please teach me how to get borth name value.

Colin Law

unread,
Jun 30, 2012, 5:17:48 AM6/30/12
to rubyonra...@googlegroups.com
My first question would be why are you using find_by_sql? Why not use
the normal rails ActiveRecord methods. See
http://guides.rubyonrails.org/active_record_querying.html
and
http://guides.rubyonrails.org/association_basics.html

I assume you have already worked through the getting started guide and
some tutorials such as railstutorial.org which is free to use online.

Colin

tanizawa

unread,
Jun 30, 2012, 9:37:33 AM6/30/12
to rubyonra...@googlegroups.com
I almost use normal ActiveRecord methods.
I use find_by_sql for complected sql.

2012年6月30日土曜日 18時17分48秒 UTC+9 Colin Law:

Colin Law

unread,
Jun 30, 2012, 10:33:47 AM6/30/12
to rubyonra...@googlegroups.com
On 30 June 2012 14:37, tanizawa <kazuy...@gmail.com> wrote:
> I almost use normal ActiveRecord methods.
> I use find_by_sql for complected sql.

Why are you joining main.id on sub.id? Normally that would be
considered poor database design. It would be usual to use a has_one
belongs_to relationship, then you could use an ActiveRecord query.
Also your table names should be plural to follow the Rails
conventions.

By the way, please don't top post, it makes it difficult to follow the
thread. Insert your reply inline. Thanks.

Colin
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Talk" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/rubyonrails-talk/-/Y0cbAv-VbxAJ.
>
> To post to this group, send email to rubyonra...@googlegroups.com.
> To unsubscribe from this group, send email to
> rubyonrails-ta...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/rubyonrails-talk?hl=en-US.

Frederick Cheung

unread,
Jul 1, 2012, 7:39:34 AM7/1/12
to Ruby on Rails: Talk
Activerecord can't tell the difference between the 2 name columns -
you need to give them distinct names e.g.

select main.id,main.name,sub.name as sub_name from main ...

Fred
Reply all
Reply to author
Forward
0 new messages