`accepts_nested_attributes_for`,但仅修改第一个孩子 [英] `accepts_nested_attributes_for`, but only modify the first child
问题描述
简要背景
我正在建立一个常规论坛来学习/练习Rails.
I'm making a conventional forum to learn/practice Rails.
User Model
has_many :topics
has_many :posts
Topic Model
has_many :posts
belongs_to :user
Post Model
belongs_to :user
belongs_to :topic
但是,当用户创建一个新主题时,我也希望他们同时在该主题中创建第一个帖子(就像论坛工作一样).此外,当主题创建者编辑主题时,他还将编辑第一个帖子.
However, when a User is creating a new Topic, I also want them to simultaneously create the first Post within that topic (just like forums work). Additionally, when the Topic creator edits the Topic, he also edits the first Post.
因此,我在主题模型中添加了accepts_nested_attributes_for :posts
.
So, I added accepts_nested_attributes_for :posts
to the Topic model.
# TopicController
def new
@topic = current_user.topics.new
@topic.posts.build
end
这是嵌套形式:
# topics/_form
<%= form_for [@topic] do |topic| %>
<%= topic.text_field :name %>
<% topic.fields_for :posts do |post| %>
<%= post.text_area :content %>
<% end %>
<% end %>
问题
此代码有效.用户将在创建主题的同时创建第一个帖子.
This code works. The User will create a first Post alongside the creation of a Topic.
但是,随着其他用户为主题创建帖子并且@topic.posts
展开,主题创建者编辑主题时,主题中每个帖子的文本区域都显示为主题创建者可编辑.
However, as other Users create Posts for the Topic and @topic.posts
expands, when the Topic creator edits the Topic, text areas for every post in the Topic appear as editable by the Topic creator.
我该如何做,以便主题创建者只能在views/topics/_form
表单上查看和编辑主题的第一篇文章?
How can I make it so the Topic creator can only see and edit the first post of the Topic on the views/topics/_form
form??
推荐答案
有用的资源: http ://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for
与topics/_form
一起为topics#edit
动作创建了一个名为_edit_form
的新局部.
Created a new partial alongside topics/_form
called _edit_form
just for the topics#edit
action.
阅读API文档(如图),我发现您可以为forms_for
指定一个实例:
Reading the API doc (go figure), I found that you can specify an instance for forms_for
:
<%= form_for @topic do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.fields_for :posts, ---->@post<---- do |p| %>
<%= p.text_area :content %>
<% end %>
</p>
<p><%= f.submit %></p>
<% end %>
在主题控制器中:
def edit
@topic = ...
@post = @topic.posts.first
end
这篇关于`accepts_nested_attributes_for`,但仅修改第一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!