【发布时间】:2011-04-02 19:38:41
【问题描述】:
我正在处理多态关联并且遇到了一些麻烦。我的模型设置如下:
class User < ActiveRecord::Base
has_one :phone, :as => :callable, :dependent => :destroy
end
class Client < ActiveRecord::Base
has_one :phone, :as => :callable, :dependent => :destroy
end
class Phone < ActiveRecord::Base
belongs_to :callable, :polymorphic => true
end
在我的用户控制器中
def create
@user = User.new(params[:user])
if @user.save
@user.phone.create(:area_code => params[:user][:area_code], :phone => params[:user][:phone])
redirect_to @user, :notice => "Account created successfully!"
else
render 'new'
end
end
在开发日志中,我看到正确插入了电话和用户的位置,但是当我去编辑用户时,表单中电话的字段为空白。这是我的编辑方法:
def edit_employee
@user = User.find(params[:id])
@title = "Edit #{@user.name}"
end
我的编辑用户表单如下所示。
- form_for @user do |f|
- if @user.errors.any?
.error_messages
%h2 Please correct the following errors
%ul
- for message in @user.errors.full_messages
%li= message
%p
= f.label :name, "Name"
= f.text_field :name
%p
= f.label :email, "Email Address"
= f.text_field :email
%p
= f.label :phone, "Phone"
= f.text_field :area_code, :style => "width: 50px;"
= f.text_field :phone, :style => "width: 100px;"
= f.label :ext, "Ext."
= f.text_field :extension, :style => "width: 60px;"
%p
= f.label :password, "Password"
= f.password_field :password
%p
= f.label :password_confirmation, "Confirm Password"
= f.password_field :password_confirmation
%p.button= f.submit
我知道我应该在这个编辑方法中添加一些东西,也许
@phone = @user.phone
但这也没有用。这是第一次使用多态关联,因此非常感谢任何帮助和指针。我观看了有关此主题的 Railscasts,但它似乎没有遵循我的基本功能。再次感谢您的帮助,如果需要更多信息,请告诉我!
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord polymorphic-associations