STI and accepts_nested_attributes_for in rails
Posted
by ryanshackintosh
on Stack Overflow
See other posts from Stack Overflow
or by ryanshackintosh
Published on 2010-04-19T12:12:30Z
Indexed on
2010/04/22
4:43 UTC
Read the original article
Hit count: 186
ruby-on-rails
I have models as follows:
class Entity < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a[:label].blank?} , :allow_destroy => true
end
class Client < Entity
before_save :set_type
private
def set_type
self.type = "Client"
end
end
class Address < ActiveRecord::Base
belongs_to :entity
end
I have recently implemented accepts_nested_attributes_for on the /clients/new form, as follows:
<% form_for(@client, :html => {:class => 'form'}) do |f| -%>
<%= f.label :name %>
<%= f.text_field :name -%>
<%= f.label :phone %>
<%= f.text_field :phone %>
<% f.fields_for :addresses do |a| %>
<%= a.label :street %>
<%= a.text_field :street%>
<%= a.label :city %>
<%= a.text_field :city %>
<% end %>
<% end %>
And my controller as follows:
class ClientsController < ApplicationController
before_filter :load_client , :except => [:index, :new, :create, :render_clients]
def new
@client = Client.new
@client.addresses.build
end
def create
@client = Client.new(params[:client])
if @client.save
flash[:notice] = 'Client has been successfully added'
redirect_to @client
else
render :action => 'new'
end
end
The issue is that when the record is saved it gives an error stating: "Entity can't be blank"
I assume it is something to do with the fact that a 'Client' and not an 'Entity' is being added.
Can anyone point me in the right direction?
© Stack Overflow or respective owner