`accepts_nested_attributes_for`, but only modify the first child

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 03:53:17

问题


A Brief Background

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.

So, I added accepts_nested_attributes_for :posts to the Topic model.

# TopicController
def new
  @topic = current_user.topics.new
  @topic.posts.build
end

And here's the nested form:

# topics/_form
<%= form_for [@topic] do |topic| %>
  <%= topic.text_field :name %>
  <% topic.fields_for :posts do |post| %>
    <%= post.text_area :content %>
  <% end %>
<% end %>

The Question

This code works. The User will create a first Post alongside the creation of a Topic.

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.

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


回答1:


Helpful resource: http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

Created a new partial alongside topics/_form called _edit_form just for the topics#edit action.

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

In the Topics Controller:

def edit
  @topic = ...
  @post = @topic.posts.first
end


来源:https://stackoverflow.com/questions/5972287/accepts-nested-attributes-for-but-only-modify-the-first-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!