【问题标题】:Error on record creation: nil object instead of array?创建记录时出错:nil 对象而不是数组?
【发布时间】:2011-01-31 01:56:38
【问题描述】:

我有一个Topic,它有很多Posts,并接受它们的嵌套属性。当我创建一个主题时,它也会创建第一个帖子。

Topics#create 被调用时,我在尝试评估nil.[]= 时得到NoMethodError,但我就是不知道是什么原因造成的。

创建方法:

@forum = Forum.find params[:forum_id]
params[:topic][:post_attributes][:member_id] = current_member.id
@topic = @forum.topics.create params[:topic]
respond_with @topic, location: topic_url(@topic)

我的新主题表单:

- @topic.posts.build
= form_for @topic do |topic_form|
  = topic_form.label :title
  = topic_form.text_field :title
  = topic_form.fields_for :posts do |post_fields|
    = post_fields.label :content
    = post_fields.text_area :content

知道什么是错的吗?

【问题讨论】:

  • 错误指向哪一行?
  • @Zabba:在复制之前,我删除了一行代码进行测试。更新了问题以包含它。第二行发生错误。
  • 你传入的参数是什么? (它们应该显示在错误页面中,向下一点)

标签: ruby-on-rails model record nested-attributes


【解决方案1】:

我的猜测是在这一行:

参数[:topic][:post_attributes][:member_id] = current_member.id

您可能应该将其更新为:

参数[:topic][:post_attributes][0][:member_id] = current_member.id

params[:topic][:post_attributes].first[:member_id] = current_member.id

由于您使用的是 has_many 关联,因此可能会提交多个帖子与主题一起提交,因此 post_attributes 的参数实际上是一个数组。

【讨论】:

  • 有没有办法模拟has_one 关联以确保只提交一个帖子?
  • 有几种方法。 1. 创建您自己的 first_post 属性或 has_one 关联,您可以将其用于此表单 - 而不是 has_many posts 关联。 2. 对 HTML 进行硬编码以仅允许一组后属性 - 最终需要更多的手动工作。我的建议是做你现在正在做的事情,然后通过检查 [:post_attributes] 的长度并确保它等于 1 且不大于 1 来验证是否只提交了一篇文章。
【解决方案2】:

Post 有很多关联吗?
也许你应该尝试:

params[:topic][:posts_attributes][0][:member_id] = current_member.id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 2016-01-07
    相关资源
    最近更新 更多