我是铁杆新手,今天我遇到了fields_for的问题。希望有人能帮助我。 我有一个模型项目:
class Project < ActiveRecord::Base
validates :project_name, presence: true,uniqueness: true
validates :plan_time, presence: true
has_many :tasks, dependent: :destroy
accepts_nested_attributes_for :tasks, allow_destroy: true
end
和模型任务:
class Task < ActiveRecord::Base
belongs_to :user
belongs_to :project
validates :user_id, presence: true
validates :project_id, presence:true
end
但是当我制作form_for项目时:
<%= form_for(@project, do |f| %>
<%= f.fields_for :tasks do |tasks_for_form|%>
<%= render 'task_fields', f: tasks_for_form%>
<%end%>
... 它在db中呈现项目的所有现有任务。请帮助我!
答案 0 :(得分:1)
fields_for
那是什么,你期待它做什么?
如果您只想要新任务的字段,那么您需要pass in a record object到构建器,例如:
<%= f.fields_for :tasks, @project.tasks.new do |tasks_for_form| %>
如果您想要添加/删除功能,您需要自己添加,请查看cocoon gem,这样做很简单。
答案 1 :(得分:0)
我不确定你是否已经部分结束,但是当fields_for已经启动时,结束是必需的。
<%= form_for(@project, do |f| %>
<%= f.fields_for :tasks do |tasks_for_form|%>
<%= render 'task_fields', f: tasks_for_form%>
<% end %>
<% end %>