Reputation: 3422
I have an application where a User can Challenge another User. A challenge has a date, a time, a place, a winner, a loser, a score it can be accepted or refused. I am thinking about the database structure I should apply. At first I have created a challenge table that looks like this :
create_table "challenges", force: :cascade do |t|
t.date "date"
t.time "time"
t.text "place"
t.text "score"
t.integer "winner"
t.integer "loser"
t.integer "referee"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "accepted", default: false
I also created a contestants join table with a user_id and a challenge_id
create_table "contestants", force: :cascade do |t|
t.integer "user_id"
t.integer "challenge_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
I am not sure this is the correct data structure as I now have a distinction in the views (different partials) between the creator of the challenge and the "recipient". Thus I now added a migration directly linking challenge to user : A challenge belongs to a user (the creator of the challenge) and a User has_many challenges. But this seems a bit redundant now with my contestants table.
What is the correct data-structure for what I want to achieve ?
Upvotes: 0
Views: 34
Reputation: 3881
There is not redundancy and this is done all the time. Have the models emulate the terminology you use in your business domain
class User
has_many :challenges #issued challenges
has_many :authored_challenges, dependent: :destroy, class_name: Challenge
end
class Challenge
belongs_to :author, class_name: User, foreign_key: 'author_id'
belongs_to :recipient, class_name: User, foreign_key: 'user_id'
end
Upvotes: 0
Reputation: 4164
You may not need the contestants table.
What about if you add two more columns to the challenge table for challenger
and challengee
or something of that nature?
Then a User can have_many challenges as challenger
and also have many challenges as challengee
.
I think you can try this approach.
Upvotes: 1