I have three tables customers, indentities and people. I hav ecreated
models for them. The are connected with foreign keys and
has_many/belongs_to in this fashion:
customers has_many: identities
identities belongs_to: customer
identities has_many: people
people belongs_to: identities
Now, I have a form in which I would like to create db entries for the
three tables. customers have a password field that needs to be equal to
the params[:passwordconfirm], otherwise none of the models should be
saved to the db.
I also have some data checks (validated_presence_of and
validates_uniqueness_of) in the models.
If the data checks or password confirmation fails, I want that the form
i displayed again so that the user can correct the errors. Else the data
shoud be saved to the db. If I input data in all required fields all is
fine, but…
My problems are:
-
If i input valid data in the required field, but type the
passwordconfirmation so that it will fail I get the error message:
ArgumentError which I guess has something to do with the “raise”-line
below. -
If I omitt some of the required fields I get the following error
message:
ActiveRecord::StatementInvalid …Column ‘customer_id’ cannot be null:
INSERT INTO identities…
The controller action looks like this. I guess the code inside the
transaction block contains errors… however I would need some help in
finding out whats wrong. Please help me!
def create_data
@customer = Customer.new
@identity = Identity.new
@person = Person.new
@identity.customer = @customer
@person.identity = @identity
if request.post?
@pwdmismatch = false
@customer.attributes = params[:customer]
@identity.attributes = params[:identity]
@person.attributes = params[:person]
undigestedPassword = @customer.password
@customer.password = MD5.md5(undigestedPassword).hexdigest
begin
@customer.transaction(@customer, @identity, @person) do
@customer.save
@identity.save
@person.save
if(undigestedPassword != params[:passwordconfirm])
@pwdmismatch = true
end
raise ActiveRecord::RecordInvalid unless
@customer.valid? && @identity.valid? && @person.valid? && (@pwdmismatch
== false)
login(@customer.username, undigestedPassword,
“identity”) #Login and redirect the user to the selected identity
end #end transaction
rescue ActiveRecord::RecordInvalid
end
end
end #end of create data
My rhtml-file uses “error_message_on”, “error_messages_for” and checking
if pwdmismatch is true to mark errors in the input data.
Like I said, I would need some help on this.
Best regards,
Daniel