开发者

Active Record accepts nested attributes for - creating record with overridden class_name

When I save the form (last piece of code shown here) I get an error saying: unknown attribute: person

I'm thinking this is because I have overridden the class name of the administrator attribute.

Any ideas?

class Event < ActiveRecord::Base
  #start_date, end_date, title
  has_one :administrator, :class_name => "Person" 
  has_one :account_manager, :class_name => "Person"
  accepts_nested_attributes_for :administrator
end

class Person < ActiveRecord::Base
  #fname, lname, bday
  belongs_to :event
end

event_controller#new

@event = Event.new
@event.build_administrator

event_controller#create

@开发者_StackOverflow中文版event = Event.new(params[:event])
#=> unknown attribute: person

view

<%= form_for @event do |f| %>
<%= f.text_field.title %>
<%= f.fields_for :administrator do |administrator| %>
<%= administrator.text_field :lname %>
<% end %>
<%= f.submit "Save" %>
<% end %>

I also notice that the field is generated with a name of event[person][lname] which will be a problem as event will need to accept nested attributes for account_manager


Edit: Came across this, and I think it's the more proper way to do it.

<%= form_for @event do |f| %>
  <%= f.text_field.title %>
  <%= f.fields_for @event.administrator, :administrator_attributes do |administrator| %>
    <%= administrator.text_field :lname %>
  <% end %>
  <%= f.submit "Save" %>
<% end %>

Less proper way, but works well:

class EventsController < ApplicationController

  before_filter :fix_administrator_attribs, :only => [:create, :update]

  # ...

  protected

  def fix_administrator_attribs 
    if params[:event][administrator]
      administrator = params[:event][:administrator]
      params[:event].delete(:administrator)
      params[:event].update({:administrator_attributes => administrator})
    end
  end

end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜