我目前正在做我的第一个 Rails 项目。我正在尝试制作一个用于与朋友上传照片的网络应用程序。因此,在创建相册的表单上,他们应该有一个选择字段,他们希望与哪些朋友共享相册。但是,我无法在选择字段中显示名称,并且出现错误
undefined method 'name' for nil:NilClass
即使我的用户数据库中有“名称”列。我是否误解了“名称”的来源?我认为诸如@users.name
意味着进入数据库并找到每个用户的名称值之类的属性?这是我的文件(如果您需要任何其他文件,请告诉我):
_form.html.erb(有错误的那个)
<%= form_for([@user, @album], :remote => true, :html => { :id => "uploadform", :multipart => true }) do |f| %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_area :description %>
<%= f.select :user, @users.name %>
<%=f.label :avatar, "Upload" %>
<%=f.file_field :avatar %>
<br>
<%=f.submit %>
</div>
<% end %>
专辑模特
class Album < ActiveRecord::Base
attr_accessible :avatar, :name
has_and_belongs_to_many :users
mount_uploader :avatar, AvatarUploader
end
用户模型
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :name, :password, :password_confirmation
validates_presence_of :password, :on => :create
validates_format_of :name, :with => /[A-Za-z]+/, :on => :create
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
validates_length_of :password, :minimum => 5, :on => :create
has_many :albums
accepts_nested_attributes_for :albums
end
配置/路由
Pholder::Application.routes.draw do
resources :users do
resources :albums
end
resources :albums do
resources :pictures
end
专辑控制器
class AlbumsController < ApplicationController
def index
@albums = Albums.all
respond_to do |format|
format.html
format.json { render json: @albums }
end
end
def show
end
def update
end
def edit
end
def create
@users = Users.all
@user = User.find(params[:user_id])
@album = @user.albums.build(params[:album])
if @album.save
flash[:success] = "Album created!"
end
end
def new
@user = User.find(params[:user_id])
@album = Album.new
end
def destroy
end
end