Kalpesh1 Patel wrote:
I want to execute below SQL query from rails:
“select T.id, F.name, I.name as image_name from Template T, Format F,
Images I WHERE F.id=T.id and I.image_id=T.image_id;”
I tried something like this:
@result = Template.find(:all, :select => “Template.id, Format.name,
Images.name as image_name”, :joins => “join Format join Images on
Format.id = Template.id and Images.image_id = Template.image_id”)
but it doesn’t work and also looking very ugly. Its like i am issuing
SQL query only but with different syntax. Is there any better way?
Thanks,
-Kalpesh
@result = Template.find(:all, :select => "Template.id, Format.name,
Images.name as image_name", :include => [:format, :image])
This assumes that you have associations like
Template
belongs_to :format
belongs_to :image
Although i’m just guessing here as your foreign key relationships are
unusual. Usually you wouldn’t have the id in one table being a foreign
key to id in another. Usually you would have templates.format_id being
a foreign key to formats.id for example.
On that subject, table names in rails are conventionally named after a
downcased underscore pluralised version of the class name. eg class
Template would use a table ‘templates’, class ‘LearningObjective’ would
use table ‘learning_objectives’ etc.