【发布时间】:2017-11-30 22:07:26
【问题描述】:
我试图让用户能够在同一个视图/控制器中更新他们的名字和个人资料照片,但不同的模型/表单/模态。如果名称更新,照片不会,反之亦然。
当我尝试更新照片时,我进入浏览器 ActionController param is missing or the value is empty: student,而控制台中什么也没有。这是我的新html:
=form_with model: @student_account do |form|
.form-group
= form.label :task_name, "Name", class: "form-control-label"
= form.text_field :first_name, id: "first_name", class: "form-control"
=form.submit " Update ", {class: "btn btn-primary float-right"}
button.btn.btn-secondary.float-right type="button" data-dismiss="modal"
= "Cancel"
.modal-body
=form_for @student, url: student_account_path, html: { multipart: true } do |form|
.form-group
= form.label :image, "Image", class: "form-control-label"
= form.file_field :image, id: "image", class: "form-control"
=form.submit " Upload ", {class: "btn btn-primary float-right"}
button.btn.btn-secondary.float-right type="button" data-dismiss="modal"
= "Cancel"
还有我的控制器:
def update
student_account = StudentAccount.find(params[:id])
# if params[:image].nil?
if params.has_key?(:first_name)
logger.debug("hitting here!")
if student_account.update_attributes(student_account_params)
flash[:notice] = 'Preferred name updated successfully.'
redirect_to(student_account_path(student_account.id))
else
flash[:alert] = student_account.errors.full_messages.to_sentence
redirect_to(student_account_path(student_account.id))
end
else
@student.update_attributes(student_image_params)
flash[:notice] = 'Photo updated successfully.'
redirect_to(student_account_path(student_account.id))
end
end
private
def student_account_params
params.require(:student_account).permit(
:first_name,
:image
)
end
def student_image_params
params.require(:student).permit(
:image
)
end
【问题讨论】:
-
你只需要一个表格。
-
为什么?我希望它们在单独的模式上
-
因为每个表单都会触发一个请求-响应周期。如果您有两种形式,那么根据定义,您将有两个请求-响应周期 - 每个模型一个。顺便说一句,没有理由一个表单不能更新多个模型——无论是相似的还是不同的类。模型、控制器和视图(包括表单)彼此之间没有 1:1 的关系。
-
模态或模型? (没关系。如果您想在一个请求中更新它们,您仍然需要在一个表单上同时更新它们。)
-
两者-我的意思是模态,但它们也是不同的模型。嗯,好吧,我会考虑尝试使它成为一种具有多种模式和模型的形式...
标签: ruby-on-rails