So I am making an app that reviews books, articles and the like.
I have created the backbone of the app by creating models, views, controllers etc for Piece(the book or article), Section(self explanatory), Subsection, and Subsubsection.
I want to add a new model into the mix, a "Links" model (which will just be a link to another source or website). My issue is that I don't know how to make ALL of my previously stated models have "Links". I want each of The above models to have access and CRUD capabilities to their "Links", but so far all i have read about is has_many or has_and_belongs_to_many.
As far as I understand, those kinds of relations only relate ONE model to ONE other model, even if Piece might have many Sections, it only relates these two models.
I guess the Links model would have to have an obligatory piece_id, but then optional id's such as: section_id, subsection_id depending on where the link was. So if in Chapter 3 of my first book i want to add a link, it would have an obligatory piece_id=1 and then a section_id=3, but then no subsection_id or subsubsection_id.
So how do I go about creating a model such that it belongs to several other models? Or is this even possible?
https://github.com/kingdavidek/StuddyBuddy
Ok, it sounds like essentially you want a polymorphic association
class Link
belongs_to :linkable, polymorphic: true
end
class Piece
has_many :links, as: :linkable
end
Link would need linkable_id integer column and linkable_type string column. You can then use it in the same way as an ordinary has_many to belongs_to association
if i wanted to create a new Link in a Subsection, it would belong to
Subsection, but also to Section and Piece because of the nested
relationship
This bit rails can't help with, you'd need to write your own method to find all the links in the chain of items.
This is a pretty good use case for polymorphic associations. For simplicity lets start out with a one to many relationship:
class Link < ActiveRecord::Base
belongs_to :linkable, polymorphic: true
end
class Piece < ActiveRecord::Base
has_many :links, as: :linkable
end
class Section < ActiveRecord::Base
has_many :links, as: :linkable
end
Here the links table will have linkable_id (int) and linkable_type (string) columns. One important thing to take note of here is that linkable_id is not a true foreign key from the RBDMS point of view. Rather ActiveRecord resolves which table the relation points to when it loads the relation.
If we want to cut the duplication we can create a module which contains the desired behavior. Using ActiveSupport::Concern cuts a lot of the boilerplate code involved in creating such a module.
class Link < ActiveRecord::Base
belongs_to :linkable, polymorphic: true
end
# app/models/concerns/linkable.rb
module Linkable
extend ActiveSupport::Concern
included do
has_many :links, as: :linkable
end
end
class Piece < ActiveRecord::Base
include Linkable
end
class Section < ActiveRecord::Base
include Linkable
end
So how would we make a polymorpic many to many relation?
class Link < ActiveRecord::Base
has_many :linkings
end
# this is the join model which contains the associations between
# Links and the "linkable" models
class Linking < ActiveRecord::Base
belongs_to :link
belongs_to :linkable, polymorphic: true
end
# app/models/concerns/linkable.rb
module Linkable
extend ActiveSupport::Concern
included do
has_many :links, through: :linkings, as: :linkable
end
end
class Piece < ActiveRecord::Base
include Linkable
end
class Section < ActiveRecord::Base
include Linkable
end
On a side note - a better way to build a hierarchy between sections would be to use a single Section model and give it a self joining relationship.
class Section < ActiveRecord::Base
belongs_to :parent, class_name: 'Section'
has_many :children, class_name: 'Section',
foreign_key: 'parent_id'
end
Related
I have a concern that creates an association:
# concerns/product.rb
module Product
extend ActiveSupport::Concern
included do
has_many :products, class_name: "Product", foreign_key: :owner_id
end
end
And an example model:
# models/user.rb
class User < ApplicationRecord
include Product
end
If I do: User.products.last it works fine. I also want to be able to do Product.last.owner but it won't work without the association being defined. I can't define it in the Product model since I have no clue to what models will include the concern that creates the association.
I have tried creating the association using inverse_of:
class Product < ApplicationRecord
belongs_to :owner, inverse_of: :products
end
... but it won't work, apparently it needs a class name.
I've also tried reflecting on which classes the concern gets included within but it raises some strange errors when the concern gets included into several different models.
How do I create the inverse of an association from within the concern?
As pointed out by #engineersmnky you can't actually setup an association that points to a bunch of different classes without using polymorphism:
# you can't have a class and a module with the same name in Ruby
# reopening the class/module will cause a TypeError
module ProductOwner
extend ActiveSupport::Concern
included do
has_many :products, as: :owner
end
end
class Product < ApplicationRecord
belongs_to :owner,
inverse_of: :products,
polymorphic: true
end
class User < ApplicationRecord
include ProductOwner
end
The information about what you're actually joining has to be stored somewhere on the products table. If you don't use polymorphism you just have an integer (or UUID) which will always refer to a single table.
I'm transitioning from "Laravel ORM" to "Rails Active Record" and I couldn't find how do you do something like this:
$this->people()->attach($person['id'], ['role' => $role]);
Explanation for Laravel code snippet
People is a polymorphic association to the class that is being accessed via $this via the Role class. The function above, creates a record in the middle table (roles/peopleables) like this:
id: {{generically defined}}
people_id: $person['id']
role: $role
peopleable_type: $this->type
peopleable_id: $this->id
How the association is defined on the Laravel end:
class XYZ {
...
public function people()
{
return $this->morphToMany(People::class, 'peopleable')->withPivot('role','id');
}
...
}
My efforts in Ruby
Here is how I made the association in Ruby:
class Peopleable < ApplicationRecord
belongs_to :people
belongs_to :peopleable, polymorphic: true
end
class People < ApplicationRecord
has_many :peopleables
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
I have seen the operation << but I don't know if there is any way to set an additional value on the pivot table while triggering this operation. [in this case the roles or peopleables tables; I use these two terms interchangeably in this app.]
PS. So, basically the question is how to define additional values on the pivot table in a polymorphic-many association in ActiveRecord and dynamically set those values while initiating an attachment relationship
Description of Functionality
Our application has a limitless [generally speaking, not that there is no computational limits!] content type: post, novel, poem, etc.
Each of these content types can be associated to individuals who play certain roles: editor, author, translator, etc.
So, for example:
X is the translator of Post#1. X, Y and Z are authors of Post#1.
There is a distinct People model and each content type has its own unique model [for example: Post, Poem, etc].
The idea of :through is referring to the 'Role class' or 'the pivot table' [whichever way you want to understand it] that the polymorphic association is recorded on it.
In addition to the information regarding a simple polymorphic relationship, there is also the kind of role that is recorded on the pivot table.
For example, X is both the author and the translator for Post#1, so there are two rows with the same people_id, peopleable_type and peopleable_id, however they have different values for role.
From what I understand given your description, I think you have this models (I'll change the names to what I understand they are, hope it's clear enough):
class Person < ApplicationRecord # using singular for models
has_many :person_roles
end
class Poem < ApplicationRecord
has_many :person_roles, as: :content
end
class Novel < ApplicationRecord
has_many :person_roles, as: :content
end
etc...
class PersonRole < ApplicationRecord
belongs_to :person
belongs_to :content, polymorphic: true
# you should have a "role" column on your table
end
So a Person is associated to a "content" (Novel, Poem, etc) via the join model PersonRole with a specific role. A Person that is the author of some novel and the editor of some peom would have two PersonRole records.
So, if you have a person and you want to assign a new role on some content, you can just do:
person.person_roles.create(role: :author, content: some_poem)
or
PersonRole.create(person: person, role: :author, content: some_poem)
or
some_poem.person_roles.create(person: person, role: :author)
You have two things in play here: "belongs_to :content, polymorphic: true" is covers the part of this being a polymorphic association. Then you have the "PersonRole" table that covers the part you know as "pivot table" (join table/model on rails).
Note that :through in rails has other meaning, you may want to get all the poems that a user is an author of, you could then have a "has_many :poems, through: :person_roles" association (that won't actually work, it's more complex than that in this case because you have a polymorphic association, you'll need to configure the association with some extra options like source and scope for this to work, I'm just using it as an example of what we understand as a has many :through association).
Rails is 'convention over configuration'. Models' must be in singular 'Person'.
ActiveRecord has has_many ... through and polymorphic association
"Assignable" and "Assignments" are more natural to read than "peoplable"
class Person < ApplicationRecord
has_many :assignments, as: :assignable
has_many :roles, through: :assignments
end
class Role < ApplicationRecord
has_many :assignments
has_many :people, through: :assignments
end
class Assignment
belongs_to :role
belongs_to :assignable, polymorphic: true
end
You can read more Rails has_many :through Polymorphic Association by Sean C Davis
I'm trying to wrap my head around how I should model my database for a parent model with many has_one associations (20+). I have one model called House which is the parent model of all the other models:
class House < ActiveRecord::Base
has_one :kitchen
has_one :basement
has_one :garage
has_one :common_room
#... Many other child models
end
All the child models contain unique properties specific to their own class. I've thought about STI, but there isn't really any shared functionality or inputs that I can use across models. I've also thought of making one 'super model', but that doesn't really follow Rails best practices, plus it would contain over 200 columns. Is there another design pattern or structure that I can use to model this efficiently so that I can reduce database calls?
class House
has_many :rooms
Room::TYPES.each do |room_type|
has_one room_type, -> { where(room_type: room_type) }, class_name: "Room"
end
class Room
belongs_to :house
TYPES = %i/kitchen basement garage common_room etc/.freeze
end
In your migration make sure to add_index :rooms, [:type, :house_id], unique: true. Unless a house can have more than 1 type of room. If that is the case, I think a different approach is needed.
To your second question, it depends really, what type of database are you using? If its PostgreSQL you could use hstore and store those as a properties hash. Or you could serialize you db to take that as a hash. Or you could have another model that room has many of. For instance has_many :properties and make a property model that would store that information. Really depends on what else you want to do with the information
Why not using Polymorphism in Rails? It would be much simpler
class House < ActiveRecord::Base
has_many :properties, as: :property_house
end
class Kitchen < ActiveRecord::Base
belongs_to :property_house, polymorphic: true
end
class Garage < ActiveRecord::Base
belongs_to :property_house, polymorphic: true
end
For more information, go here: http://terenceponce.com/blog/2012/03/02/polymorphic-associations-in-rails-32/
In my rails app, user's can create Designs.
Design.rb
belongs_to :user
User.rb
has_many :designs
I'm trying to create a new model Look so user's can create Looks. The way I envision this to work is when a user goes to /looks/new, they have a list of all the designs they have favorited (which I have that set up that variable already) in a table format with the right column being checkboxes where the user can go through and check a few of those Designs and click Create. All the Designs that have been checked would be part of that Look.
As I haven't done this sort of thing before, I need some help accomplishing this in all aspects MVC.
Look.rb
has_many :designs
Design.rb
belongs_to :looks # ??? Would the model be something different since technically when you create a design it doesn't belong to a look.
Looks Controller
def new
#designs = #user.favorites #This get's me all the designs that the particular user has favorited
#look = Look.new # ??? Again, as I haven't set this sort of relation up before, I'm unsure.
end
Please let me know any other code I can provide to help out. I may even be making this sound more complicated than it is.
This configuration should work for you Justin:
class User < ActiveRecord::Base
has_many :designs
has_many :looks, through: :designs
end
class Design < ActiveRecord::Base
belongs_to :user
has_many :designs_looks
has_many :looks, through: :designs_looks
end
class Look < ActiveRecord::Base
has_many :designs_looks
has_many :designs, through: :designs_looks
end
class DesignsLook < ActiveRecord::Base
belongs_to :design
belongs_to :look
validates :design_id, presence: true
validates :look_id, presence: true
end
I don't know what you want to do in the future but you might want to consider putting the user_id on the DesignsLook model, so you would not need a complex join query to retrieve all the Looks of a User. And also you implement shared Designs with all users
Your user has many designs. New looks can have many designs. And design can belong to MANY looks, users. Smells like has many ..., :through
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
class User
has_many :designs, through: :design_possesion
end
class Look
has_many :designs, through: :look_designs
end
class Design
has_many :look_designs, :design_possesion
end
Of course you'll have to create corresponding tables.
Hey guys,
I'm new to rails
here are the 2 ways of making a Drummer model and Cymbal model both have many videos
1st way by using polymorphic:
class Drummer < ActiveRecord::Base
has_many :videos, :as => :videoable
end
class Cymbal < ActiveRecord::Base
has_many :videos, :as => :videoable
end
class Video < ActiveRecord::Base
belongs_to :videoable, :polymorphic => true
end
2nd way by using two 1:m association:
class Drummer < ActiveRecord::Base
has_many :videos
end
class Cymbal < ActiveRecord::Base
has_many :videos,
end
class Video < ActiveRecord::Base
belongs_to :drummer
belongs_to :cymbal
end
I haven't try them in console, But I think both will work as they should. But I don't know the difference?
I believe that you must use polymorphic method because a model cannot belongs_to (one to one association) more than one other model. For more info see this rails guide: http://guides.rubyonrails.org/association_basics.html
It depends on the columns you have in your database. If you have videoable_type and videoable_id you're doing polymorphism. In that case, calling videoable on an instance of Video can return anything, it's not related to drummers or cymbals. If it is drummer_id and cymbal_id it's the latter version you described.
Both will work.
Imagine you have 5 models sharing Videos.
You would need 5 modelName_id columns in videos.
To determine which type of parent model you have on Video you would need to check each one for id presence.
Validating that only one of the ids is set would be necessary (or valuable).
Polymorphic relations are easier to maintain and expand in such cases.