Ruby on rails 返回模型和相关的多态模型
我正在处理多态关联,遇到了一些问题。我的模型设置如下:Ruby on rails 返回模型和相关的多态模型,ruby-on-rails,ruby-on-rails-3,activerecord,polymorphic-associations,Ruby On Rails,Ruby On Rails 3,Activerecord,Polymorphic Associations,我正在处理多态关联,遇到了一些问题。我的模型设置如下: 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
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 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,但它似乎没有遵循我的基本功能。再次感谢您的帮助,如果需要更多信息,请告诉我 您应该研究如何使用字段和嵌套属性 在user.rb模型中是否设置了attr_accessible?如果不是,我会添加它,因为这是一个安全问题。好的,我添加了
accepts_nested_attributes_for :phone
在用户模型中。我还在新的用户表单中添加了phone字段,如下所示
%p
- fields_for @user.phone do |phone|
= phone.label :phone, "Phone"
= phone.text_field :area_code, :style => "width: 50px;"
= phone.text_field :phone, :style => "width: 100px;"
= phone.label :ext, "Ext."
= phone.text_field :extension, :style => "width: 60px;"
但是现在我得到了ActionView::Template::Error(NilClass:Class的未定义方法'model_name')异常
是的,我的模型中有可访问的属性。我刚刚在这里放了一个非常精简的版本。请参见下文。谢谢你的回复!我修复了NilClass异常。我需要为:phone do | phone |添加f.fields|u。但还是没有运气。现在这些领域甚至不再出现了。
%p
- fields_for @user.phone do |phone|
= phone.label :phone, "Phone"
= phone.text_field :area_code, :style => "width: 50px;"
= phone.text_field :phone, :style => "width: 100px;"
= phone.label :ext, "Ext."
= phone.text_field :extension, :style => "width: 60px;"