Activerecord - how to made this? - mysql

Everyday, I need to run the a script and send all of my users an 'exam' or set of questions. I have modelled as class 'Exam' which subclasses ActiveRecord::Base. Now, how do I send user's instances of Exam?
What I was thinking was create a new class called 'ExamInstance' which would have a reference to 'Exam' and the user.
I am new to SQL and ActiveRecord so if someone can help me better model this so I can avoid problems later on or just give me some insight, that would be great.
Thanks

I'll suggest just use has_many :through create a model UserExam for many to many relation between exam and user
class User < ActiveRecord::Base
  has_many :users_exams
  has_many :exams, :through => :users_exams
end
 
class UserExam < ActiveRecord::Base
  belongs_to :users
  belongs_to :exams
end
 
class Exam < ActiveRecord::Base
  has_many :users_exams
  has_many :users, :through => :users_exams
end
For more information on has_many :through

Add 'ExamUser' model to keep track of exam and the corresponding users references. The model skeleton will look something like:
class ExamUser < ActiveRecord::Base
belongs_to :exam
belongs_to :user
end
You could then loop through the records of this table to send your questions.

You can design your new model like this..
class ExamUser < ActiveRecord::Base
belongs_to :user # user has many exams
belongs_to :exam # exam has many users
end

Related

Rails: active-records query for entry in range & included in

I am working on a shipping implementation for a checkout process.
My app has carts, cart_items, orders and order_items.
Weight and size of all items are in the database and I calculate total_weight in the order and cart models. I also have a shipping_service model with weightmin and weightmax for each shipping service + a postzone and land (country) model.
Now I would like to show on the shopping cart page only the shipping services which are conform to the weight of the cart or order.
I suppose my carts_controller should be something like:
class CartsController < ApplicationController
def show
#cart = Cart.find(params[:id])
#lands = Land.find(:all)
#shippingservices = Shippingservice.where('#cart.total_weight BETWEEN ? AND ?', :weightmin, :weightmax)
end
My cart model is:
class Cart < ActiveRecord::Base
attr_accessor :total_weight
has_many :cart_items
has_many :products, :through => :cart_items
has_many :lands
has_many :shipping_services, :through => :postzones
def total_weight
cart_items.inject(0) {|sum, n| n.weight * n.amount + sum}
end
end
My land model is
class Land < ActiveRecord::Base
has_many :shippingservices, :through => :postzones
has_many :postzones
has_many :carts
end
My shipping_service model is:
class Shippingservice < ActiveRecord::Base
has_many :lands, :through => :postzones
has_many :postzones
has_many :carts
has_many :orders
end
My postzone model is:
class Postzone < ActiveRecord::Base
belongs_to :shippingservice
belongs_to :land
end
The postzone table has foreign keys for lands and shipping_services.
Latter I would like to implement two selector fields: one for ship_to_countries and one for shipping_services, with the second selector being populate only with entries related to the entry selected in the first selector.
I had already this working inside the carts_controller:
#shippingservices = Shippingservice.includes(:lands, :postzones).where('postzones.land_id = ?', Land.first.id)
Which load only shipping services for a specific country into the second selector. But I do not know how to combine the two where clauses relative to weight and postzone into one query.
Any help is very much appreciated!
Thank you in advance.
The method total_weight is a ruby method which is defined in the model Cart
Then you cannot call this method within an SQL statement.
You need to calculate the total weight in the SQL statement.
You should try something like
#shippingservices = Shippingservice.joins(carts: :cart_items).where(
'(cart_items.weight * cart_items.amount) BETWEEN ? AND ?', :weightmin, :weightmax
)
I didn't try but I think it should work :)

Call two models dependent on each other in one controller for a view

I am new to Rails so I am going to try and explain this the best I can.
I have three models: artist, fest, and festival_artist
artist contains only an ID and an artist_name
fest contains only an ID and a festival_name
festival_artist contains an ID, a artist_id, and a festival_id
I created Fest using a scaffold so that is where my controller and show.html.erb is.
Below are my models:
class Artist < ApplicationRecord
belongs_to :festival_artist
end
class Fest < ApplicationRecord
belongs_to :festival_artist
end
class FestivalArtist < ApplicationRecord
has_many :artists
has_many :fests
end
In my fests_controller.rb I have:
def show
#festival_artists = FestivalArtist.where(festival_id: #fest.id)
end
I tried to add:
def show
#festival_artists = FestivalArtist.where(festival_id: #fest.id)
#artists = Artist.where(id: #festival_artists.artist_id)
end
However, that throws an undefined method artist_id for # error.
The goal is to display the Artist's name in the Fest's show.html.erb page for the festival that that artist belongs to.
In SQL it would be:
SELECT A.artist_name
FROM festival_artists AS FA
INNER JOIN artists AS A
ON FA.artist_id = A.id
Any suggestions? Even telling me what to Google would help out because I'm not sure my terminology is correct.
Let me know if you need anymore information.
Guess your models structure is not 100% correct. Try to check out http://guides.rubyonrails.org/association_basics.html for details.
There are to ways to handle your associations in Rails:
HABTM (has and belongs to many), as noticed in #grizzthedj answer.
has_many :through association
In this case your code will look like
class Artist < ApplicationRecord
has_many :festival_artists
has_many :fests, through: :festival_artists
end
class Fest < ApplicationRecord
has_many :festival_artists
has_many :artists, through: :festival_artists
end
class FestivalArtist < ApplicationRecord
belongs_to :artists
belongs_to :fests
end
So you can access artists in the controller
def show
#festival_artists = #fest.artists
end
I'm not sure that you need the FestivalArtist model. If you use "has_and_belongs_to_many" in Artist and Fest models, this will implement the many-to-many relation that you are looking for.
# fest.rb
class Fest < ActiveRecord::Base
has_and_belongs_to_many :artists
end
# artist.rb
class Artist < ActiveRecord::Base
has_and_belongs_to_many :fests
end

RAILS ActiveRecord::Relation how to get many-to-many though: table name

I am in my quest of overriding activerecord method, but I need to be access the table name many-to-many relationship :through . How do i do it?
For example I have model Student and Subject, to connect the two I use has_many Subjects, through: :registers.
I have a statement Student.find(1).subjects, how do i get the table name register from the activerecord statement?
Thanks
Student.rb
Class Student < ActiveRecord::Base
has_many :registers
has_many :subjects, :through => :registers
end
subject.rb
class Subject < ActiveRecord::Base
has_many :registers
has_many :students, :through => :registers
end
register.rb
Class Register
belongs_to :student
belongs_to :subjet
end
Make sure your associations added like this. And You can get your all subject lists by Student.find(1).subjects
And You can also check entries in Register table by using Register.all
You can access all the register records like below.
Register.all
From your statement "Student.find(1).subjects", if you wish to get the registers along with the subjects details, you can do as:
Student.find(1).subjects.select("subjects.name, registers.name")

Query in Ruby on Rails 4 to make a selection based on the current user

I am new to Ruby on Rails and try to make the right query. But after reading the documentation and examples I don't manage to get the right query out of it. So I hope someone can point me in the right direction.
Situation
I build an app where trainers can setup trainings, and give these trainings on several dates (the dates are called thrills), other users can subscribe for these thrills. It has the following structure: models and needed table.
My models code looks like this:
class User
has_many :trainings
has_many :thrills, through: :reservations
has_many :reservations
class Training
belongs_to :user
has_many :reservations
has_many :thrills
has_many :users, through: :thrills
class Thrill
belongs_to :training
has_many :reservations
has_many :users, through: :reservations
class Reservation
belongs_to :user
belongs_to :thrill
has_one :training, through: :thrill
On an index page I want to show all the thrills that the current user has setup sorted by date. I think I need a query that comes up with the table in the uploaded image, and from that table I can select all Thrills where current_user.id = user_id
On the search page I want to show only the trainings that have a Thrill that is not full (therefore I want to make a count of the Reservations)
I was thinking of something like this:
#thrills = Thrill.joins(:trainings).where('? = trainings.user_id, current_user.id')
or
#thrills = Thrill.where('? = #thrill.training.user_id', current_user.id).all
or
#thrills = Thrill.joins(:trainings).where(trainings: { user_id: current_user.id })
But unfortunately none of them works. Does someone have an idea how to solve this? Thanks in advance!
Usually you have these two models:
class Thrill < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :thrills
end
So for your index page what you can do is:
current_user.thrills # => ActiveRecord::Relation (can call each, map etc.)

change association from one to many to many to many

I have two models lets suppose
class A < ActiveRecord::Base
has_many :bs
end
class B < ActiveRecord::Base
belogns_to :a
end
now because of some system changes I need to convert this association to many to many some thing like this
class A < ActiveRecord::Base
has_and_belongs_to_many :bs
end
class B < ActiveRecord::Base
has_and_belongs_to_many :as
end
OR
class A < ActiveRecord::Base
has_many :cs
has_many :bs, through: :cs
end
class B < ActiveRecord::Base
has_many :cs
has_many :as, through: :cs
end
class C < ActiveRecord::Base
belongs_to :a
belongs_to :b
end
what is best way to do this and most importantly I DO NOT WANT TO LOSE MY EXISTING DATA. Existing records should automatically adopt these changes. Thanks in advance.
many to many means you have connected table(model) between two other, so you could just create this one and write relation to it, after that you could remove garbage ids from B.
A, B are not good names;)
imagine you have User and Comments, and you decide that comments can have also many users, so it can look like:
class User
has_many :comments # will be changed
has_many :user_comments
end
class UserComments
belong_to :user
belong_to :comment
end
class Comment
belong_to :user # id will be removed from table and relation will be changed
has_many :user_comments
end
# as direction for import could be something like:
User.all.each do |user|
user.comments.each do |comment|
UserComments.create user: user, comment: comment
end
end