【发布时间】:2016-02-19 18:34:29
【问题描述】:
我制作了一个表单,用户可以通过单击文本或 url 按钮动态添加嵌套表单字段。提交表单后,内容将显示在视图模板中。但是,当我在/posts/id/edit 编辑(希望然后更新)帖子时,帖子内容不会出现在编辑视图模板中 - 它是浏览器中的空白页面。
非常感谢您的帮助!谢谢!
后模型
class Post < ActiveRecord::Base
has_many :things, dependent: :destroy
accepts_nested_attributes_for :things
end
事物模型
class Thing < ActiveRecord::Base
belongs_to :post
end
架构
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
帖子控制器
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
【问题讨论】:
-
你应该有一个名为 edit.html.erb 的视图
-
抱歉 - 我愿意,它的代码与 new.html.erb 模板中的代码相同。
标签: javascript ruby-on-rails ruby forms ruby-on-rails-4