返回模型和相关的多态模型

时间:2011-04-02 19:38:41

标签: 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 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,但它似乎没有遵循我的基本功能。再次提前感谢您的帮助,如果需要更多信息,请告诉我们!

2 个答案:

答案 0 :(得分:0)

您应该考虑使用fields_for和嵌套属性。 {{3P>

您是否在user.rb模型中设置了attr_accessible?如果不是,我会添加它,因为这是一个安全问题。

答案 1 :(得分:0)

好的,我添加了

accepts_nested_attributes_for :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')异常。

是的,我的模型中有attr_accessible。我刚刚在这里放了一个非常淡化的版本。

相关问题