我想将数据显示如下;
Day1
09:00 Math
11:00 Science
Room classA (3rd floor)
Day2
10:00 English
13:00 Music
Room classB (1st floor)
样本文章表
school_id day start_time title
1 1 09:00 Math
1 2 10:00 English
1 1 11:00 Science
2 1 12:00 Physics
1 2 13:00 Music
样品室表
school_id day name detail
1 1 classA 3rd floor
1 2 classB 1st floor
2 1 classC 2nd floor
我想我应该在Rails中实现SQL如下所示来显示房间数据。
SELECT name, detail FROM rooms WHERE articles.school_id = rooms.school_id AND articles.day = rooms.day
尽管我尝试了一些代码,但是如果你能在Rails中给我最好的方法,我将不胜感激。
查看代码
<div class="row">
<% @articles.each do |a| %>
<%= a.start_time %> <%= a.title %><br>
<!-- I can't display rooms.name and rooms.detail -->
<% end %>
</div>
控制器代码
def show
@articles = Article.where(school_id: (params[:id])).order(day: :asc)
型号代码
class School < ActiveRecord::Base
has_many :articles
class Article < ActiveRecord::Base
belongs_to :school
class Room < ActiveRecord::Base
#(nothing)
模式
ActiveRecord::Schema.define(version: 20150999999999) do
create_table "rooms", force: true do |t|
t.integer "school_id"
t.integer "day"
t.string "name"
t.string "detail"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "articles", force: true do |t|
t.integer "school_id"
t.integer "day"
t.string "start_time"
t.string "end_time"
t.integer "category"
t.string "title"
t.string "contents"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "schools", force: true do |t|
t.string "title"
t.datetime "created_at"
t.datetime "updated_at"
end
如果你能给我任何建议,我将不胜感激。
答案 0 :(得分:0)
根据您的示例数据库,一个房间属于一所学校,一所学校可以有很多房间。所以你要添加
has_many :rooms
到学校班级,
belongs_to :school
到Room类。
然后,要获取给定学校的房间列表,您可以使用内置的Rails方法。您可以在控制器中执行此操作:
my_school = School.find(params[:id])
some_rooms = my_school.rooms
现在,您要根据日期属性查找文章列表。第一步可能是获得一系列uniq天。然后,您可以将该数组传递给where方法。因此,您的控制器中将包含以下代码:
days = some_rooms.map(&:day).uniq
@articles = Article.where(day: days)
这应该可以满足您的需求。活动记录查询界面指南有很多有用的东西: http://guides.rubyonrails.org/active_record_querying.html