我使用acts_as_relation设置了以下多态关联
型号代码:
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