last day (16 days later) » 

3:39 PM
1
A: Associated models and a nested form with validation not working

maxcalYour validation does not work due to a Catch-22 To apply for this job, you would have to be insane; but if you are insane, you are unacceptable. ActiveRecord models get their ID from the database when they are saved. But the validation on the nested user runs before the organization is in...

 
Use Organization.create!(...).users.create(...) instead of nested attributes in your seed file.
 
I have another validation in the organization model that now generates an error on submitting the form. I've added the check_user validation to my original post. Should I remove this validation? But then again, shouldn't I also have a validation at the model level that makes it impossible to create a new organization without a user?
Thanks Maxcal, I'm trying to understand the code (great to learn about methods such as transaction and persisted). So I guess the part inside .transaction saves the organization and then creates the user, using different param sections. If either fails .transaction rolls back organization as well as user. Am I right? It should roll back both if either organization or user is invalid or not present at all.
Then we move on to the @organization.persisted? part where we will send the emails. Because of . persisted? it only does so if a new organization is created in the db. Should we perhaps change this to if @organization.users.persisted? because the emails are sent to users? It shouldn't matter since organization is rolled back if no user is created, but still... On a different note, I assume it's not possible to overwrite/update an existing organization/user with this method (which shouldn't be) instead of always creating a new record?
 
Yes, you are correct. The transaction will roll back if either fails .
 
Would you say it's safe to remove the validate :check_user from the model file? Your code makes sure at the controller level there's a user and an organization. At the model level validates_presence_of ensures for users there's an organization. Lastly, validate :check_user would ensure at model level that there's a user for an organization (only at the moment of the creation of a new organization).
 
I have answered your questions in an edit.
I think you would need to get rid of validate :check_user since it leads to a circular argument (chicken or egg).
 
3:41 PM
Thanks for your help Maxcal! I'm going through your code right now to try it. Give me a few minutes.
 
3:56 PM
I'm afraid I can't figure it out. On signing up the form I get the error message unknown attribute '0' for Stakeholder. (in my OP Stakeholder is User) referring to the line ` @organization.stakeholders.create!(organizationnew_params[:stakeholders_attribut‌​es])` (different name for params but consistently implemented). I'll try to paste the log.
Processing by OrganizationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"**Cem3mY0vjEWVcxp***sAMXApdN4WjcYA==", "organization"=>{"org_name"=>"test55", "org_tag"=>"tes55", "stakeholders_attributes"=>{"0"=>{"email"=>"test55@example.com", "username"=>"test55", "fullname"=>"test55", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "usertype"=>"2", "org_admin"=>"true"}}}, "commit"=>"Register"}
(0.2ms) BEGIN
Organization Exists (1.2ms) SELECT 1 AS one FROM "organizations" WHERE LOWER("organizations"."org_name") = LOWER('test55') LIMIT 1
 
Ah, right I forgot that Rails gives you a hash in organizationnew_params[:stakeholders_attribut‌​es]
You would need to convert it to an array to pass it to create
ary = organizationnew_params[:stakeholders_attribut‌es].map {|key,val| val}
@organization.stakeholders.create!(ary)
 
Inside if organizationnew_params[:stakeholders_attributes].any??
Just to add a little bit background, to check that that indeed the code we are looking for fits this situation: For the action of signing up a new organization, adding 1 user DOES need to be mandatory and the organization should not be saved without it. Later a user can de removed and an organization can be without a user, but not at signup. This means the attributes in the params for stakeholder, should all be there (validation for this added to stakeholder model).
I added the code inside organizationnew_params[:stakeholders_attributes].any?.
And if I enter valid information for both organization and stakeholder, it goes well and it saves and sends the email message.
If I enter valid info for the organization, and invalid info for the stakeholder: it fails. It gives the error Validation failed: Username is too short (minimum is 6 characters), Password is too short (minimum is 6 characters) pointing to the line @organization.stakeholders.create!(ary).
So not as the appropriate flash message but as a real error: ActiveRecord::RecordInvalid in OrganizationsController#create
Same if I enter valid information for stakeholder and invalid information for organization. It generates error ActiveRecord::RecordInvalid in OrganizationsController#create ... Validation failed: Org tag is too short (minimum is 3 characters) pointing to the line @organization.save!.
 
4:13 PM
def create
  @organization = Organization.new(new_params.except(:stakeholders_attributes))

  if stakeholders_attributes.empty?
    @organisation.errors.add(:stakeholders, 'No stakeholders provided')
  end
  @organization.transaction do
    @organization.save!
    if stakeholders_attributes.any?
      @organization.stakeholders.create!(stakeholders_attributes)
    end
  end
  if @organization.persisted?
    # ...
    if @organization.stakeholders.any?
      @organization.stakeholders.each do |single_user|
# this is a bit better - I need coffee
def stakeholders_attributes
   new_params[:stakeholders_attributes].values
endq
 
Still the same I'm afraid. Saves correctly if all information valid. But with either organization or stakeholder being invalid, it gives the errors.
Just to be sure, so I now have in addition to the last private method you provided:
def create
@organization = Organization.new(organizationnew_params.except(:stakeholders_attributes))
if stakeholders_attributes.empty?
@organisation.errors.add(:stakeholders, 'No stakeholders provided')
end
@organization.transaction do
@organization.save!
if stakeholders_attributes.any?
@organization.stakeholders.create!(stakeholders_attributes)
end
end
if @organization.persisted?
if @organization.stakeholders.any?
@organization.stakeholders.each do |single_user|
single_user.send_activation_email # Method in user model file.
Sorry, it doesn't seem to show the spaces that are there in my message.
Should we use if @organization.save perhaps instead of @organization.save! ?
 
4:54 PM
No, .save! causes an error if the record is invalid, which causes the transaction to rollback. which is what your want in this case
 
So if I understand correctly: .save! should store the error in flash memory, role back, and then when rendering new show the flash messages. But instead, .save! now immediately shows the error and not as flash message but as "crash" instead.
 
The errors are stored on the model @organization.errors, which is not really the issue here
What you are getting is an exception - which a program errror
What you can do is use begin ... rescue ... end to catch the exception
begin
  @organization.transaction do
      @organization.save!
      if stakeholders_attributes.any?
        @organization.stakeholders.create!(stakeholders_attributes)
      end
    end
  end
rescue ActiveRecord::RecordInvalid
end
its just like try/catch in other languages but ruby uses really weird keywords
 
5:10 PM
I added the begin ... rescue ... end.
Submitting valid info goes well. Submitting valid organization and invalid stakeholder: it just reloads the page again, without an error message. The form still has the organization info in it, and the stakeholder part of the form has been reset/emptied.
 
I gotta go, maybe I can have a look at this tommorow
 
Okay, thanks for looking at it though. If there's progress, I'll add it to my post.
 
 
1 hour later…
6:26 PM
@fylooi suggested to raise the rollback manually. This meant replacing save! and create! with respectively save and create. The add the line for manual rollback.
This changes the transaction part of the code to:
@organization.transaction do
@organization.save
if stakeholders_attributes.any?
@organization.stakeholders.create!(stakeholders_attributes)
end
raise ActiveRecord::Rollback if [@organization, @organization.stakeholders].map(&:errors).flatten.present?
end
However, submitting the form with valid info generates the error: undefined method errors' for #<Stakeholder::ActiveRecord_Associations_CollectionProxy:0x007fe6faab5c28>`
 
6:47 PM
if @organization.users.any?
@organization.users.each do |single_user|
single_user.send_activation_email
end
flash[:success] = "Confirmation email sent."
redirect_to root_url
end
You see how the `redirect_to root_url `is inside
if @organization.users.any? which means that it won't redirect if there are no users.
 

  last day (16 days later) »