【发布时间】:2013-05-16 00:05:48
【问题描述】:
我有一个模型,User,然后是另外 2 个模型:Editor 和 Administrator 通过多态关联与用户模型相关联,所以我想要有 2 种类型的用户,他们会有不同的字段,但我需要它们共享某些功能(例如在两者之间发送消息)。
因此,我需要将用户 ID 保存在一个表中,users,并将其他数据保存在其他表中,但我希望当用户注册时,他们首先创建帐户,然后根据类型创建个人资料他们确实选择了个人资料。
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
当有人创建新用户时,他们必须使用单选按钮来选择“编辑器”或“管理员”,然后使用该参数,代码将创建编辑器或管理员配置文件。
我不确定我是否有关联权限,因为它应该是“用户有个人资料(编辑/管理员)”,但在这种情况下是“个人资料(管理员/编辑)有一个用户”。
问题:
- 关联是否适合我想要完成的任务?
- 如何将用户传递给新的编辑器方法?
我现在拥有它的方式不起作用,正如我所说,该关联似乎不正确。
感谢您的时间
【问题讨论】:
-
谢谢@SimonMcKenzie :)
标签: ruby-on-rails ruby associations polymorphism