Attempting to make it so that when a user is created, based on whether they select to be a student or a corporate, rails will create that user either a student profile or a corporate profile.
Ive tried to set it up using Polymorphic associations however cant figure out how to generate the profile at the model layer based on what is selected in the view.
Models
class User < ActiveRecord::Base
#Polymorphic Association to StudentProfile and CorporateProfile
belongs_to :profileable, :polymorphic => true
after_create :build_profile
#how do i pass which profile to build?
def build_profile
Corporateprofile.create(user: self) # Associations must be defined correctly for this syntax, avoids using ID's directly.
end
def build_profile
Studentprofile.create(user: self) # Associations must be defined correctly for this syntax, avoids using ID's directly.
end
end
Student and Corporate Profiles
class Studentprofile < ActiveRecord::Base
has_one :user, :as => :profileable, dependent: :destroy
end
class Corporateprofile < ActiveRecord::Base
has_one :user, :as => :profileable, dependent: :destroy
end
View
Here i have two radio buttons to decide which user type on the sign up form
<%= bootstrap_form_for(@user) do |f| %>
<div class="field">
<%= f.form_group :gender, label: { text: "Gender" }, help: "Are you a corporate or a student?" do %>
<p></p>
<%= f.radio_button :profileable, 1, label: "Student", inline: true %>
<%= f.radio_button :profileable, 2, label: "Corporate", inline: true %>
<% end %>
</div>
And there is no passing code on the controller (as im stuck on that). Any better suggestion or ways to fix this would be much appreciated!
Cheers
Aucun commentaire:
Enregistrer un commentaire