How to create a model from another model?

Asked

Viewed 135 times

1

I have two models. One called User and the other 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 is that every professional will be a user. Therefore, every time I register a professional, I need to automatically 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 professional user at the time of the creation of the professional. I can save the professional normally, but no user is created for him or assigned their respective user_id.

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

2 answers

1

You checked if in the method create the variable professional_params Do you have User parameters? They will be required for user creation.

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

1

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

Models:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.