开发者

Displaying data from multiple tables in Rails

I have multiple tables that are related by primary key-foreign key relationship. Also, I have models that are independent of each other on top of these tables. Now, I need a view that displays the data from multiple tables. How should I do this? Should I create a dummy model with attributes from each of the table? If so, how and where do I perform the query to these multiple tables. Any code snippets will be of great help.

To be more clear, here is an example. Assume these are the following tables.

Table1: pk, attr1, attr2, attr3, attr4, attr_fk_table2, attr_fk_table开发者_高级运维3, attr_fk_table4

Table2: pk, attr1, attr2, attr3, attr4,attr5

Table3: pk, attr1, attr2, attr3

Table4: pk, attr1, attr2, attr3

Also the models of tables 1,2,3,4 are independent. I mean to say there is no has_one or belongs_to relation between them at the model level.

Now I need a view with the following attributes

Table1:attr1, Table1:attr2, Table2:attr5, Table3:attr3, Table4: attr2

How can I do this?

Thanks


Use find_by_sql:

sql = %{
  select
    t1.attr1, t1.attr2, t2.attr5, t3.attr3, t4.attr2
  from
    Table1 t1, Table2 t2, Table3 t3, Table4 t4
  where
    t1.attr_fk_table2 = t2.pk
    and t1.attr_fk_table3 = t3.pk
    and t1.attr_fk_table4 = t4.pk
}

result = find_by_sql(sql)


It sounds like what you need to do is write a query that aggregates the data into the correct structure, then simply fetch it:

ActiveRecord::Base.connection.select_rows("
  SELECT table1.attr1, table1.attr2, table2.attr5, table3.attr3, table4.attr2
   FROM table1
   LEFT JOIN table2 ON table1.attr_fk_table2=table2.pk
   LEFT JOIN table3 ON table1.attr_fk_table3=table3.pk
   LEFT JOIN table4 ON table1.attr_fk_table4=table4.pk
").each do |row|
  # ...
end

You'll get the data back as a series of rows where item 0 is table1.attr and so forth.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜