See http://pastie.caboo.se/124961
I’m basically just trying to validate the Users.state_id field. The
Users table holds the FK to States as user.state_id, where there is a
one-to-many between States and Users.
state.rb:
class State < ActiveRecord::Base
has_many :users
end
user.rb:
class User < ActiveRecord::Base
…
belongs_to :state
…
validates_presence_of :state_id
validates_associated :state
…
end
user_controller.rb:
class UserController < ApplicationController
…
def signup
…
@user = User.new(params[:user])
return unless request.post?
@user.save!
self.current_user = @user
redirect_back_or_default(:controller => ‘/user’, :action =>
‘index’)
flash[:notice] = “Thanks for signing up!”
rescue ActiveRecord::RecordInvalid
render :action => ‘signup’
end
end
signup.rhtml:
…
<%= error_messages_for :user %>
<% form_for :user, :url => {:action => “signup” } do |f| -%>
…
<%= f.collection_select :state_id, State.find_all, :id, :name,
{:include_blank => true}, {:style => ‘background-color: rgb(255, 255,
160);’, :class => ‘form-txt2’} %>
…
development.log:
…
Processing UserController#signup (for 127.0.0.1 at 2007-12-05
09:57:40) [POST]
Session ID: 815f814a0b1d8cb815f0e047a920f142
Parameters: {“user”=>{“city”=>“”, “born_on(1i)”=>“1907”,
“postal_code”=>“”, “born_on(2i)”=>“12”, “looking_for_id”=>“1”,
“headline”=>“”, “height_inches_id”=>“1”, “password_confirmation”=>“”,
“country”=>“United States”, “have_children_id”=>“1”,
“born_on(3i)”=>“5”, “smoke_id”=>“1”, “terms_of_service”=>“0”,
“want_children_id”=>“1”, “ethnicity_id”=>“1”, “drink_id”=>“1”,
“description”=>“”, “marital_status_id”=>“1”, “body_type_id”=>“1”,
“interests_string”=>“”, “hair_color_id”=>“1”, “login”=>“”,
“password”=>“”, “religion_id”=>“1”, “email”=>“”, “state”=>“18”,
“profession”=>“”}, “typed_code”=>“”, “x”=>“30”, “y”=>“11”,
“action”=>“signup”, “controller”=>“user”, “picture”=>“”,
“preference”=>{“receive_jsh_mail”=>“1”}}
State Load (0.000000) SELECT * FROM states
…