I have the following polymorphic association set up with
acts_as_relation (GitHub - hzamani/acts_as_relation: Multi table Inheritance for rails)
Model code:
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
Migration code:
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
I’m want to be able to have a form (eventually) that will allow multiple
email addresses, addresses and so on. But I’m struggling to get it to
work. I use HAML for whoever may reply with the view code, which is a
lot more readable.
I have the form currently something like this:
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