我正在开发一个使用Rails前端将更新数据发送到Rails后端的项目。
我正在尝试修补的表单数据包括资源的更新数据,以及嵌套的子资源的更新。
在这种情况下,用户与包含编写数据的表单进行交互,编写器具有许多作业,所有作业也嵌套在表单中。
数据包含作者,一个/多个/所有作者作业或两者的潜在更新。
writer.rb
class Writer < ApplicationRecord
has_many :jobs, dependent: :destroy, inverse_of: :writer
has_many :genre_tags, dependent: :destroy
has_many :genres, :through => :genre_tags
accepts_nested_attributes_for :genre_tags, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :jobs, allow_destroy: true, reject_if: :all_blank
end
job.rb
class Job < ApplicationRecord
belongs_to :writer, inverse_of: :jobs
validates_uniqueness_of :outlet_id, scope: [:writer_id]
validates :outlet_id, presence: true
end
writers_controller.rb
def update
@writer = Writer.where(inactive:false).find(params[:id])
if @writer.update(writer_params)
render json: {writer: @writer, notice: 'Writer was successfully updated.'}
else
render json: {errors:Rails.logger.info(@writer.errors.inspect), status: :unprocessable_entity }
end
def writer_params
params.require(:writer).permit(:f_name,:l_name, :email_personal, :city, :state, :country_id,:twitter, :linkedin, :freelance, :notes, :user_id, jobs_attributes: [:id, :outlet_id, :email_work, :position, :outlet_profile, :key_contact, :_destroy, presstype_tags_attributes: [:id, :presstype_id, :_destroy]], genre_tags_attributes: [:id, :writer_id, :genre_id, :_destroy])
end
end
问题在于,当我修补此数据时,我收到验证错误:
#<ActiveModel::Errors:0x007fef651e8410 @base=#<Writer id: 2, f_name: "Chet", l_name:
"Hamper", city: "Las Vegas", state: "NV", country_id: 229,
twitter: "AndreasHale", linkedin: "andreashale",
freelance: false, flagged: nil, inactive: false,
notes: nil, created_at: "2017-02-19 15:38:55",
updated_at: "2017-02-25 16:17:18", user_id: 1,
email_personal: nil, twitter_followers: nil,
personal_website: "N/A">,
@messages={:"jobs.presstype_tags.job_id"=>["can't be blank"],
:"jobs.outlet_id"=>["has already been taken"],
:"genre_tags.genre_id"=>["has already been taken"]},
@details={"jobs.presstype_tags.job_id"=>[{:error=>:blank}], "jobs.outlet_id"=>[{:error=>:taken, :value=>2}],
"genre_tags.genre_id"=>[{:error=>:taken, :value=>6}, {:error=>:taken, :value=>9}, {:error=>:taken, :value=>10}, {:error=>:taken, :value=>11}]}>
除非我弄错了,否则ActiveRecord告诉我我正在尝试创建新的嵌套属性,即使它们已经存在。我不是要覆盖这些记录,只是当它们存在时,更新它们的属性。
有关我如何指定我不想覆盖任何内容的任何线索?
更新
事实证明我的表单数据的结构与jobs_attributes,genre_tags_attributes和presstype_tags_attributes params不匹配,所以我最终重组了我的表单以完全匹配它,现在它就像一个魅力!