Rails 3渲染部分外部视图?

时间:2012-01-24 02:30:56

标签: ruby ruby-on-rails-3 ruby-on-rails-3.1

我正在为一个滑板网站的客户工作多站点。到目前为止一切都很好,但我开始陷入整个局部的困境。我有一个网站和网站has_many:专辑(专辑也属于网站)但是当我尝试从网站主页上的网站渲染专辑时,我得到未定义的方法`model_name'为NilClass:Class ?< / p>

我正在尝试在网站/显示页面上呈现相册/ _album.html.erb,以在网站的主页上显示网站最新的相册。

相册控制器

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

网站控制器

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

网站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 %>

相册/ _album.html.erb

<%= div_for @album do %>
  <h2><%= @album.title %></h2>
   <%= image_tag @album.photo.url(:small) %>
<% end %>

我在相册控制器中遗漏了什么?

1 个答案:

答案 0 :(得分:1)

在show.html中,您需要将相册集合传递给渲染方法

<%= render :partial => 'albums/album', :collection => @site.albums %>

在_album.html.erb partial中,您需要将相册属性作为本地属性引用,如此

<%= div_for album do %>
  <h2><%= album.title %></h2>
  ...

您可以在此处详细了解部分内容3.4.5 Rendering Collections