创建记录时出错:nil 对象而不是数组?

发布于 2024-10-15 15:15:18 字数 703 浏览 4 评论 0原文

我有一个包含许多帖子的主题,并接受它们的嵌套属性。当我创建主题时,它也会创建第一篇文章。

当调用 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

知道哪里出了问题吗?

I have a Topic that has many Posts, and accepts nested attributes for them. When I create a topic it creates a first post as well.

When Topics#create is called I get a NoMethodError when trying to evaluate nil.[]=, and I just can't figure out what's causing it.

The create method:

@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)

My new topic form:

- @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

Any idea on what is wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紫竹語嫣☆ 2024-10-22 15:15:18

我的猜测是,它在这一行:

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

您可能应该将其更新为:

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

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

因为您使用的是 has_many 关联,所以可能会随该主题提交多个帖子,因此 post_attributes 的参数实际上是一个大批。

My guess is that it is on this line:

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

You should probably update it to:

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

or

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

Because you are using a has_many association there is a potential for more than one post to be submitted with the topic, therefore the params for the post_attributes are actually an array.

淡紫姑娘! 2024-10-22 15:15:18

它与邮政有很多关联吗?

也许你应该尝试:

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

Is it a has many association for Post ?

Maybe you should try with :

params[:topic][:posts_attributes][0][:member_id] = current_member.id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文