gpt4 book ai didi

ruby-on-rails - Rails 3.1 中具有相同形式的多个模型?

转载 作者:数据小太阳 更新时间:2023-10-29 07:13:05 25 4
gpt4 key购买 nike

我正在使用 Rails 3.1 并在一个论坛上工作。我有一个名为 Topic 的模型,每个模型都有许多 Post。当用户创建新主题时,他们也应该创建第一个 Post。但是,我不确定如何以相同的形式执行此操作。这是我的代码:

<%= form_for @topic do |f| %>
<p>
<%= f.label :title, "Title" %><br />
<%= f.text_field :title %>
</p>

<%= f.fields_for :post do |ff| %>
<p>
<%= ff.label :body, "Body" %><br />
<%= ff.text_area :body %>
</p>
<% end %>

<p>
<%= f.submit "Create Topic" %>
</p>
<% end %>

class Topic < ActiveRecord::Base
has_many :posts, :dependent => :destroy
accepts_nested_attributes_for :posts
validates_presence_of :title
end


class Post < ActiveRecord::Base
belongs_to :topic
validates_presence_of :body
end

...但这似乎不起作用。有什么想法吗?

谢谢!

最佳答案

@Pablo 的回答似乎有你需要的一切。但更具体地说...

首先改变你 View 中的这一行

<%= f.fields_for :post do |ff| %>

对此

<%= f.fields_for :posts do |ff| %>  # :posts instead of :post

然后在你的 Topic Controller 中添加这个

def new
@topic = Topic.new
@topic.posts.build
end

这应该让你继续。

关于ruby-on-rails - Rails 3.1 中具有相同形式的多个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7289935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com