Form question


#1

Hey all, this is a pretty simple (I think) question regarding forms

I have two models, one is message.rb

class Message < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id
end

and the second is user.rb

class User < ActiveRecord::Base
has_many :messages
end

Then I also have a form which will let me specify which User a Message
belongs to.

Content
<%= text_field 'message', 'content' %>

User
<%= select("user", "id", User.find(:all).collect {|u| [u.username, u.id] }) %>

And here’s the create method

def create
@message = Message.new(params[:message])
if @message.save
@message.user = User.find(params[:user_id])
flash[:notice] = ‘Message was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end

I can list the available users in the database, but I’m having a hard
time retrieving the value from the select box and using it to set
message.user_id
The erroneous code is probably in the create method, but I can’t figure
out what I’m doing wrong. I even tried

@message.user_id = 1 - which obviously didn’t work either.

Any takers on this pretty simple question?

Thanks!


#2

Nevermind, got it working by changing my select box to

User
<%= select("message", "user_id", User.find(:all).collect {|u| [u.username, u.id] }) %>