如果我爲鍛鍊創建新練習,那麼我的字段member_id
爲空。Rails:find_or_create relation
workout.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
exercise.erb
has_and_belongs_to_many :workouts
belongs_to :member
exercise_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
我怎麼可能添加成員進行演練?
由於提出了警告,因此可能會更好。 –
所以如果練習belongs_to成員,我會做'find_or_create_by(name:exercise_name)'它會使用同名的練習,但可能不同的「所有者」/成員? – orgertot
@orgertot是的。如果在'find_or_create_by'中包含'member_id',那麼查詢'where'子句將包含條件'where name ='foo'AND member_id = 1'。取決於你想如何設計你的系統,這可能是也可能不是你想要的。 – Mohamad