change association from one to many to many to many - mysql

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

Related

Rails has_and_belongs_to with primary key delete all records on destroy

I've 3 models in Rails 5:
Product
class Product < ApplicationRecord
belongs_to :category
has_and_belongs_to_many :stores
end
Store
class Store < ApplicationRecord
has_many :admin_users
has_and_belongs_to_many :roles
has_and_belongs_to_many :products
end
ProductsStores
class ProductsStores < ApplicationRecord
self.primary_key = :store_id
end
When I try to delete one record of the join table ProductsStores with the command ProductsStores.first.destroy all records in the join table are destroyed. Why?
Could anyone help me?
Thank you in advance!
At first, you have to understand differences between HABTM and has_many through:
http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
If you created linkedin model and wanna using this model, you have to use has_many through: association, and add to this model belongs_to :product and belongs_to :store. Then with flag dependent: :destroy you will can destroy or not destroy linked models as default.

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

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.)

Activerecord - how to made this?

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

Find all without association through association

class Campaign < ActiveRecord::Base
has_many :posts
has_many :users
end
class Post < ActiveRecord::Base
has_and_belongs_to_many :users
belongs_to :campaign
end
class User < ActiveRecord::Base
has_and_belongs_to_many :posts, :join_table => "users_posts"
belongs_to :campaign
end
If user saw this post I add him to post.users. I need find first unwatched post of user campaign. Smth like this:
current_user.campaign.posts.where('posts.users not include current_user')
MrYoshiji, Thanks a lot! You remember me about include. Before I tried join and it did not work with nil because INNER JOIN, I solved my problem with instance method:
def unwatched_post
campaign.posts.includes(:users).where('users.id != ? OR users.id IS NULL', self.id).first
end