I made a form where a user can dynamically add nested form fields by clicking a text or url button. When the form is submitted, the content displays in the view template. However, when I go to edit (& hopefully then update) a post at /posts/id/edit
, the post content does not appear in the edit view template - it's a blank page in the browser.
Would really appreciate your help! Thank you!
Post Model
class Post < ActiveRecord::Base
has_many :things, dependent: :destroy
accepts_nested_attributes_for :things
end
Things Model
class Thing < ActiveRecord::Base
belongs_to :post
end
Schema
create_table "posts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "things", force: :cascade do |t|
t.text "text"
t.string "url"
t.integer "post_id"
end
Posts Controller
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
end
def update
end
new.html.erb
<button id='addtext'>text</button>
<button id='addurl'>url</button>
<%= form_for @post, url: posts_path, html: { multipart: true } do |f| %>
<%= f.fields_for :thing do |ff| %>
<% end %>
<%= f.submit %>
<% end %>
posts.coffee
current_index = 0
addText = ->
html = """
<div>
<textarea placeholder="Write something..." name="post[things_attributes][#{current_index}][text]" id="post_things_attributes_#{current_index}_text"></textarea>
<input type="hidden" name="post[things_attributes][#{current_index}] [order]" id="post_things_attributes_#{current_index}_order" value="#{current_index}" />
</div>
"""
$("#new_post input[type='submit']").before(html)
current_index += 1
$ ->
$('#addtext').on('click', addText)
current_index = 0