嗨,
我有一个嵌套形式的问题。实际上,我有两个问题,但第二个问题很小。基本结构是这样的:
class Connectable
has_one :web_account
accepts_nested_attributes_for :web_account
end
class Person < Connectable
end
class WebAccount
belongs_to :owner, class_name => `Connectable`
end
现在,我想创建一个嵌套表单来同时创建一个 Person 和一个 WebAccount。我有以下代码:
<%= form_for @person do |f| %>
...
<%= f.fields_for web_accounts do |child| %>
....
<end>
<end>
WebAccount 的唯一重要属性是名称并且是一个字符串。
还要注意定义 child_form 时使用的复数形式。我不知道为什么,但是当我使用单数(这对我来说似乎是正确的)时,rails 只会打印出一个空表格,而使用复数就可以了。我在控制器中添加了一些代码,用 :web_account 替换表单给出的 :web_accounts 哈希条目。
更重要的是,我收到以下错误:
WebAccount(#97097470) expected, got ActiveSupport::HashWithIndifferentAccess(#83887850)
我还尝试在控制台中执行此操作,定义以下哈希:
p = { :name => "ab", :lastname => "cd", :web_account => { :name => "ab.cd" }}
但结果相同。
这是我的控制器中的代码:
def create
params[:person][:status] = Status.where(:name => params[:person][:status]).first
# Transforms the web_accounts entry into web_account
params[:person][:web_account] = params[:person][:web_accounts]
params[:person].delete(:web_accounts)
@person = Person.new(params[:person])
.... (the rest is the standard response)
end
错误在第 58 行给出,即上面代码中的 Person.new(...) 行。如果需要,我可以打印出完整的框架跟踪,但和往常一样,它相当长。
为什么这不起作用?我只是无法理解它,因为在我看来,我已经遵循了所有在线教程......这可能是继承吗?