我有三个模特
class Service < ActiveRecord::Base
has_many :service_tasks
has_many :tasks, through: :service_tasks
accepts_nested_attributes_for :service_tasks, reject_if: :all_blank,allow_destroy: true
end
class Task < ActiveRecord::Base
has_many :service_tasks
has_many :services, through: :service_tasks
enum kind: [:before, :after, :whole]
end
class ServiceTask < ActiveRecord::Base
belongs_to :service
belongs_to :task
#attribute duration
end
我不知道如何通过为每个ServiceTask选择Task和不同的持续时间来添加或删除ServiceTask到服务的表单
我试过
= form_for service, html: { class: "service-form" } do |form|
= render "shared/form_errors", object: @service
- @tasks.each do |task|
%tr.presence-times-form__day
%td.presence-times-form__day__weekday
.checkbox
= label_tag nil, class: "label" do
= check_box_tag :task_ids, task.id, @service.tasks.include?(task), :name => 'service[task_ids][]'
= label_tag :task_ids, task.name
但无法确定如何为每个ServiceTask添加持续时间
答案 0 :(得分:0)
好的,我明白了。 感谢https://stackoverflow.com/users/835935/ok32和Rails has_many through form with checkboxes and extra field in the join model
Class ServicesController
before_filter :process_service_tasks_attrs, only: [:create, :update] #_destroy param
def new
@service = current_user.services.build
Task.all.each do |task|
@service.service_tasks.new(task: task) unless @service.tasks.include?(task)
end
end
def edit
@service = current_user.services.find(params[:id])
Task.all.each do |task|
@service.service_tasks.new(task: task) unless @service.tasks.include?(task)
end
end
private
def process_service_tasks_attrs
params[:service][:service_tasks_attributes].values.each do |attr|
attr[:_destroy] = true unless attr[:task_id].present?
end
end
def service_params
params.require(:service).permit(
...
service_tasks_attributes: [:duration,:task_id, :id, :_destroy]
)
end
end
并查看
= form.fields_for :service_tasks do |task_form|
%tr.presence-times-form__day
%td.presence-times-form__day__weekday
.checkbox
= label_tag nil, class: "label" do
= task_form.check_box :task_id, { checked: @service.tasks.include?(task_form.object.task) }, task_form.object.task_id, nil
= task_form.object.task.name
%td
= label_tag nil, class: "label" do
= task_form.text_field :duration