I have one model, User
, and then 2 other models: Editor
and Administrator
associated with the user model via a polymorphic association, so I want to have 2 type of users, and they will have different fields, but I need them to share certain features (like sending messages between both).
I thus need to keep the user ids in one table, users
, and the other data in other tables, but I want that when a user signs up they first create the account and then the profile according to the type of profile they did pick.
model/user.rb
class User < ActiveRecord::Base
belongs_to :profilable, :polymorphic => true
end
model/administrator.rb
class Administrator < ActiveRecord::Base
has_one :user, :as => :profilable
end
model/Editor.rb
class Editor < ActiveRecord::Base
attr_accessor :iduser
has_one :user, :as => :profilable
end
controllers/user.rb
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
if params[:tipo] == "editor"
format.html {redirect_to new_editor_path(:iduser => @user.id)}
else
format.html { redirect_to new_administrator_path(@user) }
end
# format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
controllers/editor.rb
def new
@editor = Editor.new
@editor.iduser = params[:iduser]
respond_to do |format|
format.html # new.html.erb
format.json { render json: @editor }
end
end
def create
id = params[:iduser]
@user = User.find(id)
@editor = Editor.new(params[:editor])
@editor.user = @user
respond_to do |format|
if @editor.save
format.html { redirect_to @editor, notice: 'Editor was successfully created.' }
format.json { render json: @editor, status: :created, location: @editor }
else
format.html { render action: "new" }
format.json { render json: @editor.errors, status: :unprocessable_entity }
end
end
end
views/editor/_form.html.erb
<div class="field">
<%= f.label :bio %><br />
<%= f.text_area :bio %>
<%= f.hidden_field :iduser%>
</div>
routes.rb
Orbit::Application.routes.draw do
resources :administrators
resources :editors
resources :users
When someone creates a new user they have to pic "Editor" or "Administrator" with a radio button, then using that parameter, the code will create an Editor or Administrator profile.
I am not sure if i have the association right, because it should be "User has a profile (editor/administrator)" but in this case is "Profile (administrator/editor) has a user".
The question:
- Is the association right for what I want to accomplish?
- How could I pass the user to the new editor method?
The way i have it right now is not working, and as I said, the association doesn't seem to be right.
Thanks for the time