gpt4 book ai didi

ruby-on-rails - rails : find_or_create relation

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:47 27 4
gpt4 key购买 nike

如果我为锻炼创建新练习,我的字段 member_id 为空。

锻炼.rb

     belongs_to :member
has_and_belongs_to_many :exercises

def add_exercise_with_name(exercise_name)
self.exercises << Exercise.find_or_create_by(name: exercise_name)
end

运动.erb

has_and_belongs_to_many :workouts
belongs_to :member

运动 Controller .erb

def create
@workout = current_user.workouts.find(params[:workout_id])
@exercise = @workout.add_exercise_with_name(exercises_params['name'])
redirect_to workout_path(@workout)
end

如何为练习添加成员?

最佳答案

将 id 作为额外参数传递给该方法。

def add_exercise_with_name(exercise_name, member_id)
self.exercises << Exercise.find_or_create_by(name: exercise_name, member_id: member_id)
end

这有副作用。现在,find_or_create 调用将在查找练习时考虑 member_id。如果这是不可取的,请使用 create_with(member_id: member_id) .

self.exercises << Exercise.create_with(member_id: member_id).find_or_create_by(name: exercise_name)

此外,您可以使用 block 语法:

  self.exercises << Exercise.find_or_create_by(name: exercise_name) do |exercise|
exercise.member_id = member_id
end

关于ruby-on-rails - rails : find_or_create relation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236895/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com