Forum: Ruby on Rails Form question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Nima (Guest)
on 2007-01-21 21:54
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.

<p><label for="message_content">Content</label><br/>
<%= text_field 'message', 'content' %></p>
<p>
<label for="message_user_id">User</label><br/>
<%= select("user", "id", User.find(:all).collect {|u| [u.username, u.id]
}) %>
</p>

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!
Nima (Guest)
on 2007-01-21 23:05
Nevermind, got it working by changing my select box to

<p>
<label for="message_user_id">User</label><br/>
<%= select("message", "user_id", User.find(:all).collect {|u|
[u.username, u.id] }) %>
</p>
This topic is locked and can not be replied to.