【问题标题】:Rails 3 - Nested attributes and inheritanceRails 3 - 嵌套属性和继承
【发布时间】:2012-05-12 16:54:15
【问题描述】:

喂,

我在嵌套表单中遇到问题。实际上,我有两个问题,但第二个问题很小。 基本结构是这样的:

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(...) 行。如果需要,我可以打印出完整的框架跟踪,但和往常一样,它相当长。

为什么这不起作用?我无法理解它,因为在我看来,我已经遵循了所有的在线教程......这可能是继承吗?

【问题讨论】:

  • 请在您的创建/更新操作中包含代码。指出控制器中的哪一行给出了异常也会很有帮助。
  • 给你,我编辑了问题。感谢您的快速回复,顺便说一句:D!

标签: ruby-on-rails ruby-on-rails-3 forms inheritance nested-attributes


【解决方案1】:

您应该使用web_account_attributes 而不是web_accountDocs

在控制台中尝试:

p = { :name => "ab", :lastname => "cd", :web_account_attributes => { :name => "ab.cd" }}

【讨论】:

  • 嗯.. 你能在这里复制粘贴控制台输出吗?
  • 谢谢!它在控制台中工作,我更改了修改参数哈希的代码以将其重命名为:web_account_attributes。它现在可以在控制台和表单中使用。我仍然不完全明白为什么人们可以在网络上遇到的“标准”方法不起作用。不过还是非常感谢你!
  • web_account= 访问器是has_one 方法生成的一堆方法之一。它假定您将向其传递一个 AR 模型。
  • 我明白了。再次非常感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
  • 2019-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多