当我保存表单(此处显示的最后一段代码)时,我收到一条错误消息:未知属性:person
我认为这是因为我已经覆盖了管理员属性的类名。
有什么想法吗?
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#新
@event = Event.new
@event.build_administrator
event_controller#创建
@event = Event.new(params[:event])
#=> unknown attribute: person
视图
<%= form_for @event do |f| %>
<%= f.text_field.title %>
<%= f.fields_for :administrator do |administrator| %>
<%= administrator.text_field :lname %>
<% end %>
<%= f.submit "Save" %>
<% end %>
我还注意到该字段的生成名称为 event [person] [lname] ,这将是一个问题,因为事件需要接受account_manager的嵌套属性
答案 0 :(得分:1)
编辑:遇到这种情况,我认为这是更合适的方法。
<%= 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 %>
不太合适,但运作良好:
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