Home inserting scores data into a quiz_user join table
Reply: 1

inserting scores data into a quiz_user join table

Dhaval Chheda
Dhaval Chheda Published in 2017-11-07 11:01:05Z

I am working on a quiz app and I have to keep track of users along with the quizzes that they appeared for any their score for that quiz so I thought that creating a join table (has_and_belongs_to_many relationship)quizzes_user which will have the quiz_id, user_id and the score might be the best way to go about it but I am not able to insert the scores into the table..

any help will be highly appreciated..

max Reply to 2017-11-07 12:29:12Z

Don't use has_and_belongs_to_many use has_many through:.

class User < ApplicationRecord
  has_many :results
  has_many :quizzes, through: :results

class Result < ApplicationRecord
  belongs_to :user
  belongs_to :quiz

class Quiz < ApplicationRecord
  has_many :results
  has_many :users, through: :results

Since a has_and_belongs_to_many association does not have a model for the join entities there is no straight forward way to query it directly or add additional columns to the join table.

Here you would create the "result/score" by something like:

@quiz.results.create(user: current_user, score: 99)

has_and_belongs_to_many is only actually a good idea if you know that you'll never need those features and the memory savings from not instanciating join models. This is only the case if the join entity is not an actual "thing" in itself.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.432006 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO