I am working on a multisite for a client for a skateboarding website. So far everything is great but I am starting to get stuck on the whole partial thing. I have a site and site has_many :albums(Album also belongs to site) but when I try to render albums from a site on the sites homepage i get undefined method `model_name’ for NilClass:Class?
I have am trying to render albums/_album.html.erb on the sites/show page to display a site latest’s album on the homepage of the site.
Albums Controller
class AlbumsController < ApplicationController
def index
@albums = Album.all
end
def show
@album = Album.find(params[:id])
end
def new
@album = Album.new
end
def edit
@album = Album.find(params[:id])
end
def create
@album = current_site.albums.build(params[:album])
if @album.save
redirect_to albums_path, :notice => 'Album was successfully created.'
end
end
def update
@album = Album.find(params[:id])
if @album.update_attributes(params[:album])
redirect_to album_path(@album), :notice => 'Album was successfully updated.'
end
end
def destroy
@album = Album.find(params[:id])
@album.destroy
end
end
Sites Controller
class SitesController < ApplicationController
def index
@sites = Site.all
end
def show
@site = Site.find_by_subdomain!(request.subdomain)
end
def new
@site = Site.new
end
def edit
@site = Site.find(params[:id])
end
def create
@site = Site.new(params[:site])
if @site.save
redirect_to @site, :notice => 'Signed up!'
end
end
def update
@site = Site.find(params[:id])
if @site.update_attributes(params[:site])
redirect_to @site, :notice => 'Site was successfully updated.'
end
end
def destroy
@site = Site.find(params[:id])
@site.destroy
end
end
Site Show.html
<p id="notice"><%= notice %></p>
<p>
<b>First name:</b>
<%= @site.first_name %>
</p>
<p>
<b>Last name:</b>
<%= @site.last_name %>
</p>
<p>
<b>Subdomain:</b>
<%= @site.subdomain %>
</p>
<%= render :partial => 'albums/album'%>
<%= link_to 'Edit', edit_site_path(@site) %> |
<%= link_to 'Back', sites_path %>
Albums/_album.html.erb
<%= div_for @album do %>
<h2><%= @album.title %></h2>
<%= image_tag @album.photo.url(:small) %>
<% end %>
Am I missing something in my albums controller?
In your show.html, you need to pass in the collection of albums to the render method
Within the _album.html.erb partial, you need to reference the album attribute as a local attribute, like so
You can read more about partials here 3.4.5 Rendering Collections