Reputation: 11
So I have two classes called Student and Classroom. It is a many to many relationship so my model is
class Student< ApplicationRecord
has_many :student_classrooms
has_many :classrooms, :through => :student_classrooms
end
class Classroom< ApplicationRecord
has_many :student_classrooms
has_many :students, :through => :student_classrooms
end
class StudentClassroom< ApplicationRecord
belongs_to :student
belongs_to :classroom
end
My controller in Student is
class CoursesController < ApplicationController
def new
@student = Student.new
end
def create
@student = Student.new(course_params)
if @student.save
flash[:success] = "Student created!"
redirect_to @student
end
end
def show
@student = Student.find(params[:id])
@name = @student.name
#@classroom = Classroom.find_by(name: @name) <--
end
...
end
My question is how do I get the classroom locations of a student and store it into a variable so I am able to show it on a webpage.
Upvotes: 1
Views: 186
Reputation: 20263
Use:
def show
@student = Student.find(params[:id])
@name = @student.name
@classrooms = @student.classrooms
end
That'll give you an ActiveRecord::Relation
object which you can do further where
statements on. Or, you could use it in your view to iterate and show all the student's classrooms.
Mark has it right, in your show.html.erb
you can do something like:
<% @classrooms.each do |classroom| %>
<%= classroom.name %>
<% end %>
If you want something more than just the name (like maybe the classroom number), I would recommend going with a _classroom.html.erb
partial. Which you would use something like:
<% @classrooms.each do |classroom| %>
<%= render partial: 'classroom', locals: {classroom: classroom} %>
<% end %>
I would also recommend spending a few minutes and learning/converting to HAML. So, you can have a show.html.haml
file that looks more like:
- @classrooms.each do |classroom|
.classroom-container{id: classroom.id}
= render partial: 'classroom', locals: {classroom: classroom}
Or, for Mark's example:
%ul
- @classrooms.each do |classroom|
%li
= classroom.name
Isn't that much prettier? And, you save yourself all that hassle of typing out annoying erb syntax. And no having to remember to close tags! HAML is full of rainbows and smells like cotton candy!
Upvotes: 1
Reputation: 10998
In your show method:
def show
@student = Student.find(params[:id])
@name = @student.name
@classrooms = @student.classrooms
end
Then in your app/views/students/show.html.erb
file, you could do something like this:
<ul>
<% @classrooms.each do |classroom| %>
<li><%= classroom.name %></li>
<% end %>
</ul>
This would print all the classroom names for the student you are viewing as an unordered list.
Upvotes: 0