Reputation: 27507
I'm currently working on my first rails project. I am trying to make a web app for uploading pics with friends. So on the form for creating an album, they should have a select field for which friends they want to share the album with. However, I am having trouble showing the names in the select field, and am getting an error
undefined method 'name' for nil:NilClass
even though my user database has the column "name" in it. Am I misunderstanding where "name" comes from? I thought attributes such as @users.name
would mean go into the database and find me the name values of each user? Here are my files (let me know if you need any other files):
_form.html.erb (the one with the error)
<%= 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 %>
album model
class Album < ActiveRecord::Base
attr_accessible :avatar, :name
has_and_belongs_to_many :users
mount_uploader :avatar, AvatarUploader
end
user model
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
config/routes
Pholder::Application.routes.draw do
resources :users do
resources :albums
end
resources :albums do
resources :pictures
end
albums controller
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
Upvotes: 0
Views: 2234
Reputation: 3779
Pay close attention to the error, it can be confusing at first:
undefined method 'name' for nil:NilClass
It says "for nil:NilClass" not "user123:User" That means the object you are calling the #name method on is a nil object not a User object. The error is due to the @user instance variable not being set, so @user is nil instead of an actual user. So I'm guessing params[:user_id] is not being sent properly.
Upvotes: 2