【发布时间】:2014-10-12 12:30:55
【问题描述】:
我有一个应用程序允许所有者(但不是公共用户)上传相册文件和照片。在编写视图时,我注意到一些奇怪的事情。在我的相册/index.html.erb 文件中的 do 块中,如果我传入变量 @album.id,我会得到 NilClass 的 NoMethodError。但是,如果我删除“ @",(或完全删除该变量),它工作正常。
但在我的专辑/show.html.erb 文件中,在用于编辑专辑标题的代码的 link_to 行中,我需要传递“@album.id”(或完全省略变量)以便它工作。
为什么会这样?
这是我的相册/index.html.erb 文件和代码
<div class="admin_login"><%= link_to "Admin Login", new_album_path %></div>
<div class="home"><%= link_to "Home", root_path %></div>
<h1>Albums Gallery</h1>
<% @albums.each do |album| %>
<div>
<%= link_to album.name, album_path(album.id) %>
</div>
<% end %>
这是我的专辑/show.html.erb 文件:
<h3><%= link_to @album.name %></h3>
<div class="album">
<%= link_to "Edit", edit_album_path(@album.id) %>
<%= link_to "Delete", @album, method: :delete, data:{confirm: "Are you sure you want to delete this album? All photos in it will be permanently deleted!"} %>
</div>
<br><%= link_to "Back", albums_path %>
为清楚起见,这是我的相册控制器代码:
class AlbumsController < ApplicationController
def index
@albums = Album.all
end
def new
@album = Album.new
end
def create
@album = Album.new(album_params)
@album.save
redirect_to albums_path
end
def show
@album = Album.find(params[:id])
end
def edit
@album = Album.find(params[:id])
end
def update
@album = Album.find(params[:id])
if @album.update(album_params)
redirect_to album_path(@album.id)
else
render 'edit'
end
end
def destroy
@album = Album.find(params[:id])
@album.destroy
redirect_to albums_path
end
private
def album_params
params.require(:album).permit(:id, :name, :category)
end
end
【问题讨论】:
-
注意:如果我在 index.html.erb 文件的 do 块中完全省略 (album.id) 并且如果我还完全省略了 show.html.erb 文件中 link_to "Edit" 代码中的 (@album.id)。所以这激发了我的好奇心。
标签: ruby-on-rails variables ruby-on-rails-4 views