Active Record 接受嵌套属性 - 使用覆盖的 class_name 创建记录
当我保存表单(此处显示的最后一段代码)时,我收到一条错误消息:未知属性:人员
我认为这是因为我覆盖了管理员属性的类名。
有什么想法吗?
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
@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 %>
我还注意到该字段是用 event[person][lname] 名称生成的,这将是一个问题,因为事件需要接受 account_manager 的嵌套属性
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
@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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:遇到了这个,我认为这是更正确的方法。
不太正确的方法,但效果很好:
Edit: Came across this, and I think it's the more proper way to do it.
Less proper way, but works well: