2017-03-23 14 views
0

私はエクササイズとルーチンの両方を備えたレールトレーニングアプリを構築しています。私は、各ルーチンがいくつかの演習(has_many:exercises)で構成されることを望みますが、演習は必ずしもルーチンに属している必要はありません。それを行う方法はありますか?モデルをオプションで別のモデルに属するようにするための方法はありますか?

答えて

3

guidesを読むことは、常に良いスタートです。これはRails 5以降で動作します。

belongs_to :routine, optional: true 
0

多対多リレーションシップではなく、多対多リレーションシップが必要です。

エクササイズは、任意の数のルーチンに関連付けられ、ルーチンが1つ以上のエクササイズに関連付けられることを望みます。

あなたはこのようなもので終わる:

# app/models/routine.rb 
class Routine < ActiveRecord::Base 
    has_and_belongs_to_many :exercises 
end 

# app/models/exercise.rb 
class Exercise < ActiveRecord::Base 
    has_and_belongs_to_many :routines 
end 

# db/migrate/1213123123123_create_exercises_routines_join_table.rb 
class CreateExercisesRoutinesJoinTable < ActiveRecord::Migration 
    def self.change 
    create_table :exercises_routines, :id => false do |t| 
     t.integer :exercise_id 
     t.integer :routine_id 
     t.index [:category_id, :routine_id] 
    end 
    end 
end 
関連する問題