【发布时间】:2013-11-04 18:45:59
【问题描述】:
我有一个属于_个人资料模型的工作模型。个人资料有很多工作。我有一个嵌套模型表单,用户可以在其中添加作业。表单已成功添加作业,但无法编辑/更新。相反,当我尝试编辑作业时,它会保留旧版本的作业,但也会添加新版本。它不会用新版本替换旧版本。我该如何解决?我很确定这与编辑/更新控制器有关。
编辑控制器:
def edit
@profile = current_user.profile
end
更新控制器:
def update
#if current_user.profile.jobs.any?
@profile = current_user.profile.update_attributes(profile_params)
if current_user.profile.invalid?
@profile = current_user.profile
render :edit, :status => :unprocessable_entity
else
redirect_to profile_path(current_user.profile_name)
end
end
问题是,更新控制器适用于非嵌套信息,它只是不适用于嵌套作业。以下是强参数:
def profile_params
params.require(:profile).permit(:title,
:category, :description, :state, :zip_code, :rate,
jobs_attributes: [:firm, :position, :category, :description,
:begin, :end, :_destroy])
end
这是配置文件模型:
class Profile < ActiveRecord::Base
belongs_to :user
has_many :jobs
accepts_nested_attributes_for :jobs , :reject_if => :all_blank, :allow_destroy => true
end
另外,如果有帮助,这是我的路线:
resources :profiles do
resources :jobs
end
提前感谢您的帮助。
编辑
以下是创建操作的参数:
{"jobs_attributes"=>{"1383593195849"=>{"firm"=>"1st firm", "position"=>"1st position",
"category"=>"1st category", "description"=>"1st description", "begin"=>"1999",
"end"=>"1999", "_destroy"=>"false"}}}
以下是更新时同一作业的参数:
{"jobs_attributes"=>{"0"=>{"firm"=>"1st firm", "position"=>"1st position",
"category"=>"1st category", "description"=>"1st description", "begin"=>"1999",
"end"=>"1999", "_destroy"=>"false"}, "1"=>{"firm"=>"1st firm",
"position"=>"1st position", "category"=>"1st category",
"description"=>"1st description", "begin"=>"1999", "end"=>"1999", "_destroy"=>"1"}}}
编辑:
这是我的看法。我不认为他们是问题的一部分。
= simple_form_for @profile do |f|
%h3 Jobs
#jobs
= f.simple_fields_for :jobs do |job|
= render 'job_fields', :f => job
.links
= link_to_add_association 'add job', f, :jobs
= f.submit
这里是“job_fields”部分:
.nested-fields
= f.input :firm
= f.input :position
= f.input :category
= f.input :begin
= f.input :end
= f.input :description
= f.input :_destroy, as: :boolean, inline_label: 'Delete box'
= link_to_remove_association "remove task", f
【问题讨论】:
-
发布更新动作的参数
-
参数中有两个作业需要更新。这就是它的本意吗?你能发表你的看法吗?
-
link665,不,它不应该是那样的。这就是问题所在,而不是更新对象,而是创建一个新实例。我现在将发布意见。
-
simple_fields_for方法是什么? -
@link664 来自 Simple Forms gem。谷歌会很好的。
标签: ruby-on-rails ruby-on-rails-4 rails-activerecord nested-forms nested-attributes