# Validating a form with a foreign key

**URL:** <https://www.ruby-forum.com/t/validating-a-form-with-a-foreign-key/189053>\
**Category:** Rails\
**Created:** [May 23, 2010, 10:44am UTC](https://www.ruby-forum.com/t/validating-a-form-with-a-foreign-key/189053 "2010-05-23T10:44:51Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![wpvanpaassen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/6f9a4e/32.png) [@wpvanpaassen](https://www.ruby-forum.com/u/wpvanpaassen)\
**Post date:** [May 23, 2010, 10:44am UTC](https://www.ruby-forum.com/t/validating-a-form-with-a-foreign-key/189053/1 "2010-05-23T10:44:51Z")

</div>

Hi there.  
I have a problem with validating a form, where is foreign key present.  
I have a table like this:  
id  
name  
password  
status\_id

This is the way that status\_id is implemented to the users table.

## \<%= select\_tag (‘status\_id’, options\_for\_select([[’-- choose one –’, nil]] + @status.collect { |stat| [stat.status, stat.id]}, @user.status\_id))%\>

## When I dont enter anything to any of the fields, I get an error: NoMethodError in Users#create Showing users/\_form.rhtml where line #12 raised: You have a nil object when you didn’t expect it! You might have expected an instance of Array. The error occurred while evaluating nil.collect Extracted source (around line #12): 12: \<%= select\_tag (‘status\_id’, options\_for\_select([[’-- choose one –’, ‘’]] + @status.collect { |stat| [stat.status, stat.id]}, @user.status\_id))%\>

## And when everything is “not blank” just the status\_id is nto chosen, I get another error: ActiveRecord::RecordNotFound in UsersController#create Couldn’t find Status with ID=

Here is the code of my controller:  
class UsersController \< ApplicationController  
def index  
@user = User.find(:all)  
end  
#\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* NEW  
def new  
@user = User.new  
@status = Status.find(:all)  
end

def create  
@user = User.new(params[:user])

```
status = Status.find(params[:status_id])
@user.status = status

if @user.save
  flash[:notice] = 'New item successfully created!'
  redirect_to(:action => 'index')
else
  flash[:notice] = 'Creating an item failed!'
  render(:action => 'new')
end

```

## end end

Can you suggest a solution???
