SamuraiBlue
SamuraiBlue

Reputation: 861

Rails4: How to display the data in many has_many models

I'd like to develop an app for schedule. Each user create their own schedule.

I'd like to display the data as followings;

schedule title (user name)

  day1(mm/dd,yyyy)
    09:00 Math
    11:00 Science
    Room name A

  day2(mm/dd,yyyy)
    10:00 Physics 
    13:00 Music
    Room name B

Although I can display the schedule title and user name, I couldn't display the date(mm/dd, yyyy) and room name. (I haven't make a model for course name and time)

It would be appreciated if you could give me any suggestion.

user.rb

class User < ActiveRecord::Base
  has_many :schedlues
  ...

schedule.rb

class Schedule < ActiveRecord::Base
  belongs_to :user
  has_many :rooms
  ...

room.rb

class Room < ActiveRecord::Base
  belongs_to :schedlue

schema

create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    ...
end

create_table "schedules", force: :cascade do |t|
    t.string   "title"
    t.integer  "user_id"
    ...
end

create_table "rooms", force: :cascade do |t|
    t.date     "date"
    t.string   "room_name"
    t.integer  "schedule_id"
    ...
end

I haven't made a model for course name, time yet.

users_controller.rb

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    @schedules = @user.schedules.paginate(page: params[:page])
  end
  ...

show.html.erb

    <% if @user.schedules.any? %>
      <ol class="schedules">
        <%= render @schedules %>
      </ol>
      <%= will_paginate @schedules %>
    <% end %>

_schedule.html.erb

<li>
  <span class="content"><%= schedule.title %>(<%= schedule.user.name %>)</span>
  #Although I tried to display date and room name here, I couldn't.
</li>

Upvotes: 1

Views: 63

Answers (1)

Arslan Ali
Arslan Ali

Reputation: 17802

You need to use has_many + through relationship over here.

See, a user has_many schedules, and one schedule has many rooms. So indirectly a user has_many rooms as well. You gotta write the following line of code in User model:

class User < ActiveRecord::Base
  has_many :schedules
  has_many :rooms, through: :schedules
end

Now, you can directly call rooms on a user object like following:

user = User.last
user.rooms.each do |room|
  puts room.room_name # calling it simply `name` would be more appropriate.
end

Upvotes: 1

Related Questions