首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有办法在ROR表单中创建数量不定的嵌套资源?

有没有办法在ROR表单中创建数量不定的嵌套资源?
EN

Stack Overflow用户
提问于 2018-01-24 10:17:21
回答 1查看 106关注 0票数 0

我有一个创建锻炼例程的表单,它还可以将练习创建为锻炼例程的嵌套属性。我将其设置为创建10个练习。但是,如果用户没有填写所有10个字段,则将为其余练习创建空白数据。ROR表单有没有办法在不创建任何空白数据的情况下创建任意数量的嵌套资源?请注意,该解决方案只能使用ruby/rails,不能使用javascript。下面是表单中的代码:

代码语言:javascript
运行
复制
<%= f.label :exercise %><br />
<%= f.collection_select :exercise_ids, Exercise.all, :id, :name %>
<%= f.fields_for :exercises, workout_routine.exercises do |exercises_form| %>
  <li>
    <%= exercises_form.label :name %>
    <%= exercises_form.text_field :name %>

    <%= exercises_form.label :sets %>
    <%= exercises_form.text_field :sets %>

    <%= exercises_form.label :reps %>
    <%= exercises_form.text_field :reps %>

    <%= exercises_form.label :target %>
    <%= exercises_form.text_field :target %>
  </li> 
<% end %>

下面是控制器操作的代码:

代码语言:javascript
运行
复制
def new
  @workout_routine = WorkoutRoutine.new 
  @workout_routine.exercises.build 
  @workout_routine.exercises.build
  @workout_routine.exercises.build
  @workout_routine.exercises.build
  @workout_routine.exercises.build
  @workout_routine.exercises.build
  @workout_routine.exercises.build
  @workout_routine.exercises.build
  @workout_routine.exercises.build
  @workout_routine.exercises.build
end




def create
  @workout_routine = WorkoutRoutine.create(workout_routine_params)
  if @workout_routine.save
    redirect_to workout_routine_path(@workout_routine)
  else
    flash[:notice] = "Workout Routine cannot have the same name as an existing routine"
    render :new
  end
end 

下面是用于添加嵌套属性的自定义编写器方法,位于workout_routine.rb中:

代码语言:javascript
运行
复制
def exercises_attributes=(exercise_attributes)
  exercise_attributes.values.each do |exercise_attribute|
    exercise = Exercise.find_or_create_by(exercise_attribute)
    self.exercises << exercise
  end
end
EN

回答 1

Stack Overflow用户

发布于 2018-01-24 10:35:46

是的,只使用Rails就可以做到这一点。在WorkoutRoutine模型中,您需要拒绝空白的练习,如下所示:

代码语言:javascript
运行
复制
# models/workout_routine.rb

class WorkoutRoutine < ApplicationRecord
  has_many :exercises
  accepts_nested_attributes_for :exercises, reject_if: lambda { |attributes| attributes[:name].blank? }
end

此外,您还可以将#new action中的10行相同代码替换为:

代码语言:javascript
运行
复制
10.times { @workout_routine.exercises.build }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48413834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档