Ruby on rails Rails:查找或创建关系
如果我为训练创建了一个新的练习,则我的字段Ruby on rails Rails:查找或创建关系,ruby-on-rails,ruby,ruby-on-rails-4,relational-database,Ruby On Rails,Ruby,Ruby On Rails 4,Relational Database,如果我为训练创建了一个新的练习,则我的字段成员id为空 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 练习_contr
成员id
为空
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
练习_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
我如何才能为练习添加成员?在您的
训练中尝试此选项
型号:
def add_exercise_with_name(exercise_name, member)
self.exercises << Exercise.find_or_create_by(name: exercise_name, member: member)
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
此外,还可以使用块语法:
self.exercises << Exercise.find_or_create_by(name: exercise_name) do |exercise|
exercise.member_id = member_id
end
self.exercises如果遵循关联,则外键将自动填充。
在控制器中,您还可以通过关联使用ActiveRecord请求:
class Member < ActiveRecord::Base
has_many :workouts
has_many :exercises, through: :workouts
end
class Workout < ActiveRecord::Base
belongs_to :member
has_and_belongs_to_many :exercises
end
class Exercise < ActiveRecord::Base
belongs_to :member
has_and_belongs_to_many :workouts
end
class ExercisesController < ActionController::Base
before_action :get_workout
def create
@workout.exercises.where(name: exercises_params['name']).first_or_create
redirect_to workout_path(@workout)
end
private
def get_workout
@workout = current_user.workouts.find(params[:workout_id])
end
end
类成员
由于指出了警告,这个答案可能更好。因此,如果练习属于成员,我将执行find\u或\u create\u by(name:exercise\u name)
它将使用名称相同但可能不同的“owner”/member?@orgertot yes的练习。如果将成员id
包含在查找或创建人中,则查询where
子句将包含两个条件其中name='foo'和member\u id=1
。这可能是您想要的,也可能不是您想要的,这取决于您想要如何设计您的系统。
self.exercises << Exercise.create_with(member_id: member_id).find_or_create_by(name: exercise_name)
self.exercises << Exercise.find_or_create_by(name: exercise_name) do |exercise|
exercise.member_id = member_id
end
class Member < ActiveRecord::Base
has_many :workouts
has_many :exercises, through: :workouts
end
class Workout < ActiveRecord::Base
belongs_to :member
has_and_belongs_to_many :exercises
end
class Exercise < ActiveRecord::Base
belongs_to :member
has_and_belongs_to_many :workouts
end
class ExercisesController < ActionController::Base
before_action :get_workout
def create
@workout.exercises.where(name: exercises_params['name']).first_or_create
redirect_to workout_path(@workout)
end
private
def get_workout
@workout = current_user.workouts.find(params[:workout_id])
end
end