【问题标题】:Return Model and Associated Polymorphic Models返回模型和相关的多态模型
【发布时间】: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


    【解决方案1】:

    您应该考虑使用fields_for 和nested_attributes。 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

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

    【讨论】:

    • 请见下文。感谢您的回复!
    【解决方案2】:

    好的,我添加了

    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 (undefined method `model_name' for NilClass:Class) 异常。

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

    【讨论】:

    • 好吧,我修复了 NilClass 异常。我需要添加 f.fields_for :phone do |phone|。但仍然没有运气。现在这些字段甚至不再显示了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2020-11-14
    • 2017-01-06
    • 2016-06-09
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多