How to create a template from another template?

1

I have two models. One called User and another called Professional, where:

#user.rb
class User < ActiveRecord::Base
has_one :professional
accepts_nested_attributes_for :professional
end

and

#professional.rb
class Professional < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end

My business rule says that every professional will be a user. Therefore, every time I register a professional, I automatically need to create a user and assign it to the respective professional. In my ProfessionalsController, in the action of new and create I did the following:

#Professionals_controller.rb
class ProfessionalsController < ApplicationController
  def new
    @professional = Professional.new
    @professional.build_user
    respond_with(@professional)
  end

  def create
    @professional = Professional.new(professional_params)
    @professional.save
    respond_with(@professional)
  end
end

The problem is that this way I can not create the user of the professional when the professional is created. I can save the professional normally, but no user is created for it nor assigned to its user_id .

What am I doing wrong? Any advice for that kind of situation?

    
asked by anonymous 05.01.2015 / 18:58

2 answers

1

Have you checked whether the professional_params variable has the User parameters in the create method? They will be needed for user creation.

Are you using the User model in the new of Professionals view? If not, I think a better way is to put User creation on create method and remove the @professional.build_user call.

    
05.01.2015 / 21:21
1

If User has_one Professional, then Professional has a user_id field. If you want you can reverse the association order, and use accepts_nested_attributes in a template. An alternative to your problem would be:

Templates:

class Professional < ActiveRecord::Base
  has_one :user
  accepts_nested_attributes_for :user
end

class User < ActiveRecord::Base
  belongs_to :professional
end

View:

<%= form_for(@professional) do |p| %>
  <%= p.fields_for(@user) do |u| %>
    <%= u.name %>
  <% end %>
<% end %>

Controller:

class ProfessionalsController < ApplicationController
  def create
    professional_params #"professional"=>{"user"=>{"name"=>"John"}}
    user_params = professional_params[:user]
    user = User.create(user_params)
    professional = Professional.create(professional_params)
    professional.user = user
    professional.save!
  end
end
    
05.01.2015 / 23:03