【发布时间】:2015-03-04 14:33:42
【问题描述】:
我试图在创建父(项目)记录时自动创建子记录(参与者)。我可以很好地创建父级(项目),并且在其他表单上,我可以创建子级(参与者)。我似乎无法与父级同时创建子级(参与者)。
我在 Rails 4 上,所以我仔细设置了我的强参数。我只是不明白我做错了什么。
父控制器:
class ProjectsController < ApplicationController
def new_project
@title = params[:ti]
@project = Project.new
@project.participants.build
end
def create_project
@project = Project.new(project_params)
@template = Template.find(params[:t])
@project.participants.build
@title = params[:ti]
respond_to do |format|
if @project.save
@project.participants.save
format.html { redirect_to new_milestones_path(:p => @project.id), notice: 'Great! We saved your project details.' }
else
format.html { redirect_to new_project_path(t: @template.id, ti: @title)
}
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
def project_params
params.require(:project).permit( :id, :title, :starts, participants_attributes: [:id, :email, :title, :status, :project_id])
end
end
型号:
class Participant < ActiveRecord::Base
belongs_to :project, inverse_of: :participants
........
end
class Project < ActiveRecord::Base
has_many :participants, dependent: :destroy, inverse_of: :project
accepts_nested_attributes_for :participants, allow_destroy: true, reject_if: proc { |a| a["email"].blank? }
.........
end
表格:
<%= form_for @project, url: create_project_path(ti: @title), html: { :multipart => true, :class=> "form-horizontal", id: "basicForm" }do |f| %>
<%= f.fields_for :participants do |ff|%>
<%= ff.hidden_field :email, :value => current_user.email %>
<%= ff.hidden_field :title, :value => 'Organizer' %>
<%= ff.hidden_field :status, :value => 'accepted' %>
<% end %>
<%= f.text_field :title, :placeholder => 'Your Project Title'%>
<%= f.text_field :starts, :placeholder => 'mm/dd/yyyy'%>
<%= f.submit ' SAVE PROJECT' %>
<% end %>
更新: 我按照 Samo 的建议添加了@project.participants.build(并且我已经更新了上面的代码),这使得 fields_for 可见......但我的项目没有保存......它重定向回 new_project_path。
【问题讨论】:
-
在做嵌套表单时,我通常还必须将
<association>_attributes添加到attr_accessible列表中。所以在你的情况下,attr_accessible :participants_attributes。不确定 Rails 4 中是否仍然如此。此外,您的create操作中不应该需要@participant = Participant.new。这没有做任何事情。 -
谢谢,但 attr_accessible 不再需要了……它已被强参数取代.....stackoverflow.com/questions/17371334/…
-
您的参与者字段是否显示在表单上?
标签: ruby-on-rails forms ruby-on-rails-4 nested-attributes fields-for