What I'd like to do is to display the data as followings;
- Display
a.title
ifa.title
exists but@school.rooms.where(day: d).first.name
doesn't exist - Display
@school.rooms.where(day: d).first.name
ifa.title
doesn't exist but@school.rooms.where(day: d).first.name
exists
It works if both data exist.
Although I tried some code such as exist?
, nil?
and so on, I couldn't.
It would be appreciated if you could give me the best way in Rails.
View code
<div class="row">
<h1 class="col-md-12"><%= @school.title %></h1>
</div>
<div class="row">
<% @school.days.each do |d| %>
<h3>Day<%= d %></h3>
<% @school.articles.where(day: d).each do |a| %>
<strong><%= a.title %></strong></p>
<% end %>
<p>Room: <%= @school.rooms.where(day: d).first.name %></p>
<% end %>
</div>
Controller code
class SchoolsController < ApplicationController
def show
@school = School.find(params[:id])
end
end
Model code
class School < ActiveRecord::Base
has_many :articles
has_many :rooms
def days
self.articles.pluck(:day).uniq
end
end
class Article < ActiveRecord::Base
belongs_to :school
end
class Room < ActiveRecord::Base
belongs_to :school
end
Schema
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
It would be appreciated if you could give me any suggestion.