我有四个型号:
-
User
-
Exercise
-
Result
-
UsersExercise
我正在尝试在模型之间建立关联,这使我能够制作ORM语句:
User.first.exercises.first.barbell_push
我要获得的是User
的每个exercise
,然后获得barbell_push
结果。
以下是我当前的模型和关联:
UsersExercise
表:
create_table :users_exercises do |t|
t.integer :user_id
t.integer :exercise_id
t.date :date
t.timestamps null: false
end
模型:
class UsersExercise < ActiveRecord::Base
belongs_to :user
belongs_to :exercise
end
Exercise
表:
create_table :exercises do |t|
t.integer :dead_lift_id
t.integer :barbel_push_id
t.integer :dumbbels_curl_id
t.timestamps null: false
end
模型:
class Exercise < ActiveRecord::Base
has_many :dead_lift, class_name: 'Result', foreign_key: 'exercise_id'
has_many :barbel_push, class_name: 'Result', foreign_key: 'exercise_id'
has_many :dumbbell_curl, class_name: 'Result', foreign_key: 'exercise_id'
has_many :users_exercises, dependent: :destroy
has_many :users, through: :users_exercises
end
Result
表:
create_table :results do |t|
t.integer :reps
t.integer :weight
t.integer :exercise_id
t.timestamps null: false
end
模型:
class Result < ActiveRecord::Base
belongs_to :exercise
end
User
模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable,
:trackable, :validatable, :confirmable, :omniauthable, :omniauth_providers => [:google_oauth2]
ROLES = [:admin, :user, :trainer, :dietician]
has_many :sent_messages, :class_name => "Message", :foreign_key => "sender_id"
has_many :received_messages, :class_name => "Message", :foreign_key => "receiver_id"
has_many :users_exercises
has_many :exercise, through: :users_exercises
end
我认为您只需要一个表(您已经有:用户)
create_table :exercises do |t|
t.integer :user_id
t.string :name
t.integer :weight
t.integer :reps
t.date :check_in_time
t.date :check_out_time
t.timestamps null: false
end
"名称"列将是barbell_push,dumbell_curl等,从您的表格中获得的收集字段。从一个练习到另一个练习时,这将需要check_in和check_out,但这应该非常简单。有了这个,您确实可以得到:
@user.barbell_push.date
@user.barbell_push.duration (time elapsed from check-in to check-out)
@user.barbell_push.reps
@user.barbell_push.weight
@user.dumbell_curl.reps
etc in whatever sequence you want to present the data.