I have a model Building that has many residents. My index page list all buildings with a link to list all residents from that building. I'm learning ROR again, and I'm struggling to create this view.
Here is what I got so far.
../models/building.rb
class Building < ApplicationRecord
has_many :residents
end
../models/resident.rb
class Resident < ApplicationRecord
belongs_to :building
end
..controllers/buildings_controller.rb
Here is where I start to get lost. In my show action I don't know how to pass the params to generate a view with all residents from a building using link_to. I'm not sure how I can do it. Or how to do a query like r = Resident.all.where(:building_id => 1), but dynamically.
class BuildingsController < ApplicationController
def index
@building = Building.all
end
def show
@building = Building.find(params[:id])
@buildings = Building.all
end
..views/buildings/index.rb
<% @building.each do |b| %>
<div>
<%= link_to b.name, '/buildings/show/'b.id %>
</div>
<% end %>
I'm open to different approaches...
Thank you community!
CodePudding user response:
You should take a look at the named routes feature in Ruby on Rails: https://guides.rubyonrails.org/routing.html#path-and-url-helpers
Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of resources :photos: photos_path returns /photos
new_photo_path returns /photos/new
edit_photo_path(:id) returns /photos/:id/edit (for instance, edit_photo_path(10) returns /photos/10/edit)
photo_path(:id) returns /photos/:id (for instance, photo_path(10) returns /photos/10)
Each of these helpers has a corresponding _url helper (such as photos_url) which returns the same path prefixed with the current host, port, and path prefix.
So to be able to reach your controller, you have to add some routes to your routes.rb file and use it in your view:
# routes.rb
resources :buildings
resources :residents
# index view
<% @building.each do |b| %>
<div>
<%= link_to b.name, building_path(b) %>
</div>
<% end %>
# show view to show all residents, belonging to a building
<% @building.residents.each do |resident| %>
<div>
<%= link_to resident.name, resident_path(resident) %>
</div>
<% end %>