Home>

I want to create a Spot model as a child model of the Post model, receive values ​​in the same form, and be able to save the Post content and Spot address at the same time.

No record is created in Spot, only Post is created.

Corresponding source code

posts_controller

def new
    @post = Post.new
    @ post.spots.build
  end
  def create
    @post = current_user.posts.build (post_params)
    @ post.save
    redirect_to ("/ posts/index")
  end
..
..
..
  private
  def post_params
    params.require (: post) .permit (: content,: image, spot_sattributes: [: address])
  end


post.rb

has_many: spots, dependent:: destroy
accepts_nested_attributes_for: spots

spot.rb

belongs_to: post


new.html.erb

<% = form_for @post do | f |%>
    
    <% = f.text_area: content%>
    <% = f.fields_for: spots do | s |%>
      <% = s.text_field: address%>
    <% end%>
    
  <% = f.submit "Post", class: "btn btn-primary"%>
<% end%>
  • Answer # 1

    Records are now saved after changing post_params in posts_controller to:

    def post_params
      params.require (: post) .permit (: content,: image, spots_attributes: [: address])
    end