多态性和嵌套属性

时间:2012-04-05 11:05:04

标签: sql ruby-on-rails polymorphism nested-attributes

我使用acts_as_relation

设置了以下多态关联

polymorphic association

型号代码:

class Email < ActiveRecord::Base
  belongs_to :detail
  validates_presence_of :address
end


class Detail < ActiveRecord::Base
  acts_as_superclass
  has_many :emails
  accepts_nested_attributes_for :emails, allow_destroy: true
end

class User < ActiveRecord::Base
  acts_as :detail
  validates_presence_of :username, :password
end

迁移代码:

class CreateInfo < ActiveRecord::Migration
  def change
    create_table :details, :as_relation_superclass => true do |t|
      t.timestamps
    end
  end
end

class CreateEmails < ActiveRecord::Migration
  def change
    create_table :emails do |t|
      t.string :address
      t.string :address_type
      t.string :detail_id

      t.timestamps
    end
  end
end

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :username
      t.string :password

      t.timestamps
    end
  end
end

我希望能够拥有一个允许多个电子邮件地址,地址等的表单(最终)。但我正努力让它发挥作用。我使用HAML代表可以使用视图代码回复的人,这些代码更具可读性。

我的表格目前是这样的:

views/users/_form.html.haml

= form_for(@user) do |f|
  - if @user.errors.any?
    #error_explanation
      %h2
        = pluralize(@user.errors.count, "error")
        prohibited this user from being saved:
      %ul
        - @user.errors.full_messages.each do |msg|
          %li= msg
  .field
    = f.label :name
    = f.text_field :name
  .field
    = f.label :username
    = f.text_field :username
  .field
    = f.label :password
    = f.text_field :password
  = f.fields_for :emails do |ff|
    .field
      = ff.label :address, 'Email address'
      = ff.text_field :address
    .field
      = ff.label :address_type, 'Type'
      = ff.text_field :address_type
  .actions
    = f.submit

1 个答案:

答案 0 :(得分:1)

如果您在添加nested_attributes时遇到问题,查看https://github.com/ryanb/nested_form

可能会很有趣