Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I improve these relationships (Rails Association question) ?

Ignacio Alonso asked in Databases

Im trying to make a project to practice more kinds of associations would you kindly help me understand this?

The basic idea is to have a betting game where one user generates a new bet that can only be accepted by another user (only 2 competitors assigned for each bet, the creator and the other player).

I’m thinking about 2 tables:

users

bets

Normally I would just have a one to many relationship for the user that created the bet. But I’m confused about the ‘competitor’ column where another user is also a user with a user_id. How can I express this relationship better than this:

After thinking it through it doesn’t look like a good setup because I’m renaming a column where I’m storing the user_id and having a many to many ‘through’ model doesn’t make sense since it is a “only one competitor can participate in that bet”.

I was thinking about a ‘one to one through’ creating a ‘competitors’ table like so:

Could you explain to me how to build it in a better way?

Many thanks!

Reply

Your Bet model would have two belongs_to associations (one for the creator and one for the backer or however you'd like to call them):

class Bet < ApplicationRecord
  belongs_to :creator, class_name: 'User'
  belongs_to :backer, class_name: 'User'
end

Your bets table would need two columns for the user's id. With the above snippet, you would need a creator_id and a backer_id column.

And then if you wanted to access the bets from a user (created and backed bets for example) you would create two has_many associations on the User model:

class User < ApplicationRecord
  has_many :created_bets, foreign_key: 'creator_id', class_name: 'Bet'
  has_many :backed_bets, foreign_key: 'backer_id', class_name: 'Bet'
end

Hope that makes sense.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 78,890+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.