views:

19

answers:

1

I have four models with the following example:
User has one A, B, or C.
User.user_type = "A"
User.user_type_id = 12
In combination, the user_type and user_type_id identifies the table and record a particular user is tied to (in this example our user is connected to record #12 in table A).

On the user/new form, the user decides what user type they are, and the form passes params[:user_type] containing "A", "B", or "C" to Users controller/:create.

Based on params[:user_type] passed to Users/create, I need to build a new A, B, or C. This is what I've got so far:

Users controller, create:
if @user.save # user_type is present, user_type_id is not
  if @user.user_type == "A"
    @a = A.new.save(false) # build a new A and bypass validation
    @user.user_type_id = @a.id # set user's user_type_id.
    @user.save(false) # minor update so save without validation
  elsif @user.user_type == "B"
    ...
  elsif @user.user_type == "C"
    ...
  end
end

This code is incorrectly giving me "2" for user_type_id every time. I know that I'm going about this generally the wrong way but I don't know how to do it most concisely. Any advice?

------EDIT------
I do have polymorphic associations set up. My current set up is:
User belongs_to :authenticable, :polymorphic => true
A has_many :users, :as => :authenticable (similar for B and C)

A: 

Hi try to add validations into your User model (presence of user type) and in save action

a = params[:user_type].constantize.new.save(false)
@user.user_type_id = a.id
@user.save!

and did you use polymorphic associations ?

Bohdan Pohorilets