【发布时间】:2015-10-14 07:58:51
【问题描述】:
因此,尽管我之前已经成功使用过 cocoon,但我还是比较新的,无论出于何种原因似乎都无法让它通过参数(我尝试过使用两个不同的应用程序以及在 fedora 22 和 mac 10.10 上) .4)。
对于上下文,我一直在 .erb 中使用标准的 rails 表单,并且有 :post 和 :post_items 目前只有一个描述。我正在使用茧 1.2.6。
所以在 application.js 我有
//= require cocoon
在 post.rb 中
class Post < ActiveRecord::Base
has_many :post_items
accepts_nested_attributes_for :post_items, :reject_if => :all_blank, :allow_destroy => true
validates :title, :post_items, presence: true
validates :title, length: {maximum: 255}
end
在 post_item.rb 中
class PostItem < ActiveRecord::Base
belongs_to :post
end
我的相关控制器是(posts_controller.rb):
def index
@post = Post.new
end
def create
params[:post][:ip_address] = request.remote_ip
@post = Post.create(post_params)
if @post.save
flash[:success] = "Your post was successfully created"
redirect_to @post
else
flash[:failure] = "There was an error saving your post"
render 'index'
end
end
private
def find_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :tags, :hits, :ip_address, post_items_attributes: [:id, :description, :_destroy])
end
最后在我看来,我有 (_form.html.erb)
<%= form_for @post, html: {multipart: true} do |f| %>
<% if @post.errors.any? %>
<p>There were <%= @post.errors.count %> errors</p>
<% @post.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
<% end %>
<!-- a bunch of fields here -->
<div class="six columns">
<h3>Add images</h3>
<div id="post_items">
<% f.fields_for :post_items do |post_item| %>
<%= render 'post_item_fields', f: post_item %>
<% end %>
<div class="links">
<%= link_to_add_association 'Add Image', f, :post_items, class: "add-button" %>
</div>
</div>
<%= f.button :submit, class: "button submit-button" %>
<% end %>
最后是 _post_item_fields.html.erb
<div class="nested-fields">
<div class="field">
<%= f.label :description %>
<%= f.text_area :description %>
</div>
<%= link_to_remove_association "Remove", f %>
</div>
有修改 html 的 CSS 文件,但除了自动构建的以外,我没有 js。我已经被这个问题困扰了好几天了,我不知道出了什么问题。我已经尝试了没有验证代码的 post.rb,但它仍然不起作用。
我唯一的线索是,当您打印出参数时,它已经删除了 post_items 参数,而对于我来说,我无法弄清楚为什么。
感谢您的帮助!
编辑:为了提供信息,我添加了我的迁移。
在 db/migrate/20150722191917_create_post_items.rb 中
class CreatePostItems < ActiveRecord::Migration
def change
create_table :post_items do |t|
t.string :description
t.belongs_to :post, index: true, foreign_key: true
end
end
end
在 db/migrate/20150722173629_create_posts.rb 中
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.string :tags
t.integer :hits, null: false, default: 0
t.string :ip_address
t.timestamps null: false
end
add_index :posts, :ip_address
end
end
如果重要的话,我在生成它们时没有使用脚手架
【问题讨论】:
-
你遇到了什么错误?
-
另外,您的 post_items.html.erb 文件命名是否正确?它需要是 _post_items.html.erb 才能作为部分工作
-
哦,是的,我写的文件名与我偶然保存的不同;我将快速编辑帖子以包含我使用的正确部分名称
-
所以字段显示但未正确保存?
-
是的,所以没有错误,它只是不会将 post_items 保存到帖子中。否则页面会正确加载,如果我删除验证,它将创建一个帖子,它不会包含 post_items。
标签: ruby-on-rails ruby-on-rails-4 cocoon-gem