I'm rather confused by the construction and have tried several ways to get the following situation to work for my test. But I can't get it to work.
This is what I want:
When an activity is being made. Several clients can be assigned to that activity. Therefore creating access to #oneActivity.clients or #oneClient.activities.
Should I put up a references :client in my activity migration or the other way around? And which of the two should have to belongs_to in the model and which the has_many?
well if a client has many activities and an activity has many clients then i suggest you take a look at has_and_belongs_to_many relationship.in that case
in your Client model you would have
has_and_belongs_to_many :activities
and in your Activity Model you would have
has_and_belongs_to_many :clients
that way you can do the actions you described in your question
You can check out relationships from the rails guides here: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
I guess, from what you describe, that you need a many-to-many relationship. Clients can have many activities, and activities can, as you describe, be assigned to several clients.
Setting up such a relationship is described in the following question When should one use a "has_many :through" relation in Rails?
in your Client model you would have
has_and_belongs_to_many :activities
and in your Activity Model you would have
has_and_belongs_to_may :clients
Related
In my application, I have a User model and Artist model. Both users and artists should be able to "follow" multiple artists. I'm not really sure how to describe this relationship, and I'm completely lost regarding the underlying migration.
I've tried having has_and_belongs_to_many :artists in both classes, and an additional has_and_belongs_to_many :users in Artist, but that seems really messy, and I don't know how to write the migration.
I've looked at the association docs for the migration; I'm not sure if it would be simpler to have a third-class and use a :through association, or if I would need one for user-to-artist and another for artist-to-artist, or if one additional class would be enough.
Help appreciated, thanks in advance!
I have read the Choosing Between has_many :through and has_and_belongs_to_many on the Rails website, however I am a bit confused since I have a different case to the ones given on the website.
I have two models: Prop and CharacterCostume, and the character's costume can have multiple props associated to it, but a prop doesn't belong to that character and it can be used by any number of characters in the scene, too.
Right now I have has_and_belongs_to_many :props inside my CharacterCostume model, which does exactly what I want it to do: it fetches all the props associated with the costume using a table named character_costumes_props when I call CharacterCostume#props
However the association name is putting me off because of the "belongs to many" part. The costume does not belong to any of the props, so there's no has_and_belongs_to_many :character_costumes inside the Prop model.
I know that it can all function fine without it, but it got me thinking that maybe I should use a has_many :through association, but that requires me to create a superfluous model (it is superfluous, right?) and the model would look like this:
class CharacterCostumeProp < ActiveRecord::Base
belongs_to :character_costume
has_one :prop
end
Also, would has_one instead of belongs_to work here?
I want the code to be as semantic as possible, but I am not sure if this will increase the requirement for resources or decrease performance in some way, since there's an intermediate model.
Are there certain quirks/benefits attached to either approach? Is mine good enough? Or is my thinking completely wrong from what I need to do?
Thanks!
I think you want to use a :has_many, :through because you're going to want to work directly with the relation model - what scene(s), consumed or damaged, etc.
But, the reason it reads funny to you is that, for the most part, has_many and belongs_to don't really mean what they mean in English. What they really mean is "They have the foreign keys" and "I have the foreign key", respectively; the exception being the :dependent => :destroy behavior.
That still doesn't really help with has_and_belongs_to_many, since you're then saying, "They have the foreign keys and I have the foreign keys` - except that you can think of it sort of adding a new part both to "I" and "They" that happens to be the same part for each, and has those keys.
Does that help?
The single most important question you must ask yourself when deciding between HABTM and has_many :through is this:
Do I want to store any information specific to the association?
Example 1: magazine subscriptions
A many-to-many relationship between readers and magazines might conceivably be structured as a HABTM or a has_many :through. However, the latter makes far more sense in this case because we can easily think of information specific to the association that we might want to store.
A reader is related to a magazine through a subscription, and every subscription can be described by fields such as price, starting date, issue frequency and whether it's active or not.
Example 2: tags
The relationship between an existing Tag model and, say, an Article model is clearly of the many-to-many kind. The fact that one particular tag has been associated to any particular article must have no influence on whether the same tag will be able to be similarly associated to other articles in the future.
But, differently from the previous example, here the association itself is all the information we need. We just need to know which tags are associated to any given article. It doesn't matter when the association was formed. It doesn't matter how long it lasted.
It may matter to us how many articles a tag is associated with. But that information is stored in the Tag model since it's not specific to an association. There is even a Rails feature that takes care of that called counter_cache.
has_one wouldn't work, you'd need belongs_to
it is not superfluous if you have logic in your association model
has_and_belongs_to_many is good enough for you
See example below
class Student
has_and_belongs_to_many :courses
has_many :teachers, through: :courses
end
class Teacher
has_many :courses
has_many :students, through: :courses
end
class Course
has_and_belongs_to_many :students
belongs_to :teacher
def boring?
teacher.name == 'Boris Boring'
end
end
In the example above, I make use of both versions. See how Course would have its own logic? See how a class for CourseStudent might not? That's what it all comes down to. Well, to me it is. I use has_many through for as long as I can't give a proper name to my association model and/or the model doesn't need extra logic or behavior.
I’m creating an app that allows a user to create a course and include different types of resources (document, video, quiz) in the course. I’m having a hard time figuring out the best way to set up association between a course and its resources.
Right now, I have:
class Course < AR::Base
has_many :documents
has_many :videos
has_many :quizzes
end
class Document <AR::Base
belongs_to :course
end
class Video <AR::Base
belongs_to :course
end
class Quiz <AR::Base
belongs_to :course
end
Documents, Videos, and Quizzes all have some common attributes (e.g., name, description) but also many attributes that differ. I considered using STI and having them inherit from a single class called “Lessons.” I decided against this approach because I need multiple controllers for each class.
Ultimately, I want to be able to perform operations on all the resources that belong to a course so for example list all the documents, videos, and quizzes together and display them as a sortable list.
Any suggestions on how best to set up this model. It seems as if I could do it two ways:
Reverse polymorphic has_one association (see example)
Multiple Table inheritance (see example)
I’m a rails noob so I’m having a hard time evaluating which approach is best for this situation. Any advice would be appreciated!
Ultimately, I want to be able to perform operations on all the resources that belong to a course so for example list all the documents, videos, and quizzes together and display them as a sortable list.
Either approach is doable, but when I read this requirement, it seems you'd be best off with STI. STI is a natively supported feature in rails and allows you to query and manipulate different types of resources within the same collection.
Newbie question, beware! I'd like to implement a basic many-to-many relationship in Rails and I'm trying to find out which approach is considered the most "rails way" of them. In a traditional non-ActiveRecord DB I'd just created two tables and a junction table and written a bunch of logic to make sure all three tables are taken in consideration when operations are performed on any of them.
This is my first time using an ORM and so I'm trying to find out if perhaps ActiveRecord somehow simplifies the process for you, perhaps by not requiring a junction table to be manually created.
Railscasts seems like a reputable source of Rails wisdom, are the two ways in this cast truly "Rails way" or can I do better? - http://railscasts.com/episodes/47-two-many-to-many
There's basically two ways: has_and_belongs_to_many (habtm) and has_many with a :through option that points to another association. Both require join tables; the latter is what we call a join model, because you typically add more information to the join.
For example, consider an application with a User model who bookmarks Sites. One way would be to implement it as a habtm relationship
class User < ActiveRecord::Base
has_and_belongs_to_many :sites
end
class Site < ActiveRecord::Base
has_and_belongs_to_many :users
end
user.sites << Site.find(...)
This modeling will also require creating the sites_users table, which necessarily will lack a primary key.
The problem with this is you're likely to want to store additional information on it, so you might as well go with a join model, in this case Bookmark:
class User < ActiveRecord::Base
has_many :bookmarks
has_many :sites, :through => :bookmarks
end
class Site < ActiveRecord::Base
has_many :bookmarks
has_many :users, :through => :bookmarks
#edit: adding validation for requiring at least one bookmark
validate_before_create :at_least_one_bookmark
private
def at_least_one_bookmark
errors.add_to_base("requires at least one bookmark") unless bookmarks.count > 0
end
end
class Bookmark < ActiveRecord::Base
belongs_to :user
belongs_to :site
end
user.bookmarks.create(:site => Site.find(...) )
The more common pattern is the join model approach for its versatility and better modelling, though habtms are still used somewhat. They're just so two-dimensional that you really need to examine what you're doing and make sure there isn't some richer behavior that needs to be modelled as well.
Railscasts is the most reliable source of wisdom :) Rayan Bates teach a true "rails way" to solve problems in ruby on rails applications. You should definitely do it this way.
But if you want to learn more about associations then please follow this link http://guides.rubyonrails.org/association_basics.html
Happy coding!
As others have mentioned, Rails makes this all pretty easy using either has_and_belongs_to_many or has_many though.
I wouldn't say that one is "more right" than the other, it just depends on what you need to do, specifically around how you need to manipulate the joined models. Deciding between them is discussed here.
(All those references are from the association doc already provided.)
Ruby on Rails App.
I have two kinds of users,
Company
has_many :employees #sample
Employee
has_one :company
I want to create friendships between these two models, keeping track of the requester of the relationship (.requested_relationships) and the receiver (.pending-relationships) as well as the status (accepted, pending, etc). I can easily create the relationship with a third model and has_many :through ... BUT that wouldn't allow me to track who initiated the relationship and thus distinguish between pending and requested relationships. What is the correct way to model this?
I've been playing around with a polymorphic attribute on the relationship model, but without concrete success.
you can try to use amistad gem
very good for friendship relationship and has a very good documentation that can help you out alot. just check it out