我有一个包含 3 个表单的 View ,即时间表、锻炼和练习,每个表单都表现得像一个编辑表单。所有 View 中都有一个提交(保存)按钮。
当我点击保存按钮时。在这些表单上更改的每个数据都应在单击后更新。
什么是最好的解决方案? Javascript 更新每个数据分开?怎么做 ?有没有更多的 Rails 方法可以轻松做到这一点?
我的困难是如何将所有这些模型集成到一个 View 中,而所有这些都发生在学生模型的显示( View )中。
最佳答案
如果您正在实现类似 profile
/edit
页面(您可以在其中一次保存所有记录),我会考虑两种方式是通过 Ajax 保存表单,或者使用单个提交方法来处理它们
Ajax
ajax 方法是最传统的:
- Every form you submit will go to the form's own
update
method in the backend- Each form could be handled by a single button, but it's best to split them up
#app/controllers/profile_controller.rb
def edit
@schedules = Schedule.all #-> not sure how many records you're using
@workouts = Workout.all
@exercises = Exercise.all
end
#app/views/profile/edit.html.erb
<%= form_for @schedule do |f| %>
<%= f.text_field :test %>
<% end %>
# -> other forms
<%= button_to "Save", "#", id: "save" %>
#app/assets/javascripts/application.js
$("#save").on("click", function() {
$("form").submit(); // we'll have to define the form to submit
});
单例
如果您将所有表单作为一个提交,则必须将它们全部封装在一个表单中,因为会发送不同的错误。这可以通过使用 _ 来实现,并在后端通过循环不同的参数来处理,分别保存每个参数。
我会这样做:
#app/controllers/application_controller.rb
def submit
types = %w(schedules exercises workouts)
for type in types do
type.constantize.update_attributes()
end
end
这允许您创建一个表单,其中包含在同一操作中提交的不同数据类型:
#app/views/profile/edit.html.erb
<%= form_tag profile_submit_path do %>
<%= fields_for @schedules do |f| %>
<%= f.text_field :title %>
<% end %>
# -> fields_for for the other objects
<% end %>
这将允许您将更新的对象发送到您的 Controller ,允许他们提交
关于ruby-on-rails - Rails - 多种形式,不同的模型(对象),一个提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23670468/