I have an issue with mongoid / rails relations, I know that there are a lot of topics with this kind of issue, but I don't find any that help me ..
I have these models :
class Project
include Mongoid::Document
belongs_to :owner, :class_name => 'User', inverse_of: :projects
has_many :members
end
class Member
include Mongoid::Document
belongs_to :project, inverse_of: :members
belongs_to :user
end
class User
include Mongoid::Document
has_many :projects, inverse_of: :user
end
When I try to record an user as a member, I have this error :
Mongoid::Errors::InverseNotFound (
message:
When adding a(n) User to Project#members, Mongoid could not determine the inverse foreign key to set. The attempted key was 'project_id'.
summary:
When adding a document to a relation, Mongoid attempts to link the newly added document to the base of the relation in memory, as well as set the foreign key to link them on the database side. In this case Mongoid could not determine what the inverse foreign key was.
resolution:
If an inverse is not required, like a belongs_to or has_and_belongs_to_many, ensure that :inverse_of => nil is set on the relation. If the inverse is needed, most likely the inverse cannot be figured out from the names of the relations and you will need to explicitly tell Mongoid on the relation what the inverse is.
Example:
class Lush
include Mongoid::Document
has_one :whiskey, class_name: "Drink", inverse_of: :alcoholic
end
class Drink
include Mongoid::Document
belongs_to :alcoholic, class_name: "Lush", inverse_of: :whiskey
end):
I don't understand why, I think something is wrong with the relations, and the inverses relation but I don't know how to fix this issue.
class Project
include Mongoid::Document
belongs_to :owner, :class_name => 'User', inverse_of: :projects
has_many :members
has_many :users
end
But I don't think your modeling actually will accomplish what you want. In a relational database you would use an indirect association with a join table:
class User < ActiveRecord::Base
has_many :memberships
has_many :projects, through: :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
class Project < ActiveRecord::Base
has_many :memberships
has_many :members, through: :memberships,
source: :user
end
But over in Mongoland there are no joins so we we need to use a different approach which is embedding:
class Project
# ...
embeds_many :users
end
class User
# ...
embedded_in :project
end
Or you can fake an indirect association if you need to be able to add data to the intermediate model:
class Project
# ...
embeds_many :memberships
def members
Patient.in(id: memberships.pluck(:user_id))
end
end
class Membership
# ...
field :approved, type: Boolean
belongs_to :user
embedded_in :project
end
class User
# ...
def projects
Project.where("members.user_id" => id).all
end
end
Related
I have 3 model User Project Bug. I want to create many to many relation with through. I create the relation in model i don't know it is correct or not, user have user type column which is enum type user type contain developer, manager , QA
user.user_type.manager belong to many project it has one to many relation
user.user_type.developer has many project and many project belong to developer. it has many to many realtion
project has many bugs and bugs belong to project
developer has many bugs and many bugs belong to developer
bug model
class Bug < ApplicationRecord
belongs_to :project
has_many :developers, -> { where user_type: :Developer }, class_name: 'User', through: :project, source: :bugs
end
project model
class Project < ApplicationRecord
has_many :bugs, dependent: :delete_all
has_many :developers, -> { where user_type: :Developer }, class_name: 'User', through: :users, source: :project
has_many :users //it belong to manager_id
end
user model
class User < ApplicationRecord
enum user_type: %i[Manager Developer QA]
has_many :projects
has_many :bugs
end
developer_bug model
class DevelopersBug < ApplicationRecord
has_many :bugs
has_many :users
end
project_developer model
class ProjectsDeveloper < ApplicationRecord
has_many :projects
has_many :users
end
This
has_many :developers, -> { where user_type: :Developer },
class_name: 'User',
through: :users,
source: :project
is not what you think it is. It means something on the line of:
I already have an association 'users'. The users have an association 'project'.
Please configure an association that makes both JOINs and gives me the list of projects associated to the associated users.
This association will be named "developers" and be of objects of class "User".
You can see how these instructions are inconsistent. This
has_many :projects, through: :users, source: :project
will define a list of associated projects, by jumping over users.
On the other side, this:
has_many :developers, -> { where user_type: :Developer }, class_name: 'User'
will define a direct has-many association with a subset of all the users.
Given your description, your data model seems wrong, maybe this will be better:
class User < ApplicationRecord
has_many :managed_projects, inverse_of: :manager, class_name: 'Project'
has_and_belongs_to_many :projects
has_many :bugs
end
class Project < ApplicationRecord
belongs_to :manager, class_name: 'User', inverse_of: :managed_projects
has_and_belongs_to_many :users
has_many :bugs
end
class Bug < ApplicationRecord
belongs_to :user
belongs_to :project
end
Your schema should include the three tables, and an additional many-to-many join table projects_users that holds foreign keys to both users and projects.
As rewritten has already pointed in his excellent answer out your data model is flawed. What you want instead is a join table which joins the users and projects:
class User < ApplicationRecord
has_many :project_roles
has_many :projects, through: :project_roles
end
class ProjectRole < ApplicationRecord
belongs_to :user
belongs_to :project
end
class Project < ApplicationRecord
has_many :users
has_many :projects, through: :project_roles
end
If you then want to give the user specific roles in a project you would add the enum to the join table and this is where it starts to get hairy so bear with me here:
class ProjectRole < ApplicationRecord
enum roles: [:manager, :developer, :qa]
belongs_to :user
belongs_to :project
end
class User < ApplicationRecord
has_many :project_roles
has_many :projects, through: :project_roles
has_many :project_roles_as_manager,
-> { manager }, # short for `where(role: :manager)`
class_name: 'ProjectRole'
has_many :projects_as_manager,
class_name: 'Project',
through: :project_roles_as_manager,
source: :project
has_many :project_roles_as_developer,
-> { developer },
class_name: 'ProjectRole'
has_many :projects_as_developer,
class_name: 'Project',
through: :project_roles_as_developer,
source: :project
# ...
end
This defines associations with a default scope and then joins through that association. You would then do the same thing on the other end of the assocation:
class Project < ApplicationRecord
has_many :users
has_many :projects, through: :project_roles
has_many :manager_project_roles,
-> { manager },
class_name: 'ProjectRole'
has_many :managers,
through: :manager_project_roles,
source: :user
# ...
end
Of course this is a lot of duplication which you can cut by looping over ProjectRoles.roles.keys and defining the assocations dynamically.
This is a very flexible way of modeling it which makes as few assumptions about the domain as possible. For example it allows multiple managers for a project and it allows users to have different roles in different projects.
If you want to model "bugs" as you would typically would with issues in a tracker you would create one table for the bug and a join table for the assignment:
class Bug < ApplicationRecord
belongs_to :project
has_many :bug_assignments
has_many :users, through: :bug_assignments
end
class BugAssignment < ApplicationRecord
has_one :project, through: :bug
belongs_to :bug
belongs_to :user
end
class User < ApplicationRecord
# ...
has_many :bug_assignments
has_many :bugs
end
I would like to implement properly database and associated models for my application.
I have two models: user and location. I would like them to be joined by a table due to the fact that I need to keep historic data about the association between these two entities.
Therefore, I created a join table called user_locations in addition to the foreign keys of location_id and user_id I have two additional fields which I need.
So far so good.
A new requirement has emerged and I need my location to be polymorphic.
I don't know how to set up my models properly to store to be able to have that joined table and a polymorphic association.
Here is what I came up with so far:
user.rb
class User < ApplicationRecord
has_many :locations, through: :user_locations, as: :locationable, source_type: 'User'
has_many :user_locations
end
location.rb
class Location < ApplicationRecord
belongs_to :locationable, polymorphic: true
has_many :users
end
user_location.rb
class UserLocation < ApplicationRecord
belongs_to :user
belongs_to :location
validates_presence_of :user
validates_presence_of :location
end
I found a very good tutorial/article that I think can help you here.
It would entail you doing something like:
class User < ApplicationRecord
has_many :locations
has_many :model_ones, through: :locations, source: :locationable, source_type: 'ModelOne'
has_many :model_twos, through: :locations, source: :locationable, source_type: 'ModelTwo'
And:
class Location < ApplicationRecord
belongs_to :locationable, polymorphic: true
belongs_to :user
end
Where ModelOne and ModelTwo are filled in with the models you need obviously.
I have 3 models as follows :
class User
has_many :event_series, inverse_of: :user
has_many :events, through: :event_series, inverse_of: :user
end
class EventSeries
belongs_to :user, inverse_of: :event_series
has_many :events, inverse_of: :event_series
end
class Event
belongs_to :event_series, inverse_of: :events
has_one :user, through: :event_series, inverse_of: :events
end
This is all fine.
Now I want to add a special event for each user called the 'showcase_event'.
class User
has_one :showcase_event, class_name: 'Event', inverse_of: :user
end
This isn't working because the Event model doesn't have the user directly, it's associated through EventSeries.
I'm getting an error during serialization:
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column events.user_id does not exist
I'm using fast jsonapi:
class PublicUserSerializer
include FastJsonapi::ObjectSerializer
...
has_one :showcase_event, record_type: :event, serializer: EventSerializer
...
end
It seems to me that the inverse relationship that I have between User, Event and EventSeries needs to work between User and showcase_event but I don't know how to specify that ONLY the inverse is through EventSeries
Apologies in advance for not having the best vocabulary to describe this problem.
Solved by my rubber duck.
As seen in the documentation :
The #belongs_to association is always used in the model that has the
foreign key.
So I changed my declaration of the showcase_event to this :
class User
belongs_to :showcase_event, class_name: 'Event', inverse_of: :user, optional: true
end
And problem solved
I am trying to set up a polymorphic has-many-through relationship with ActiveRecord. Here's the end goal:
Users can belong to many organizations and many teams
Organizations have many users and many teams
Teams have many users and belong to an organization
I am trying to use has-many-through instead of has-and-belongs-to-many, since I need to associate some information along with the relationships (like user role in the organization or team), so I made a join table Membership.
How would I implement this?
I would design the schema like this:
Organization has many Team
Team has many TeamMember
User has many TeamMember
TeamMember belongs to User and Team
The models will be:
organization.rb
class Organization < ActiveRecord::Base
has_many :teams
has_many :team_members, through: :teams
has_many :users, through: :team_members
end
team.rb
class Team < ActiveRecord::Base
belongs_to :organization # fk: organization_id
has_many :team_members
has_many :users, through: :team_members
end
user.rb
class User < ActiveRecord::Base
has_many :team_members
has_many :teams, through: :team_members
has_many :organizations, though: :teams
end
team_member.rb
class TeamMember < ActiveRecord::Base
belongs_to :team # fk: team_id
belongs_to :user # fk: user_id
attr_accessible :role # role in team
end
So, compare with your requirements:
Users can belong to many organizations and many teams
=> Okay
Organizations have many users and many teams
=> Okay
Teams have many users and belong to an organization
=> Okay
Btw, we don't use any polymorphic here, and TeamMember stands for Membership in your early idea!
For polymorphic association,
class User
has_many :memberships
end
class Team
belongs_to :organization
has_many :memberships, :as => :membershipable #you decide the name
end
class Organization
has_many :memberships, :as => :membershipable
has_many :teams
end
class Membership
belongs_to :user
belongs_to :membershipable, polymorphic: true
end
Note that User is indirectly associated to Team and Organization, and that every call has to go through Membership.
In my projects, I use a Relationship class (in a gem I've named ActsAsRelatingTo) as the join model. It looks something like this:
# == Schema Information
#
# Table name: acts_as_relating_to_relationships
#
# id :integer not null, primary key
# owner_id :integer
# owner_type :string
# in_relation_to_id :integer
# in_relation_to_type :string
# created_at :datetime not null
# updated_at :datetime not null
#
module ActsAsRelatingTo
class Relationship < ActiveRecord::Base
validates :owner_id, presence: true
validates :owner_type, presence: true
validates :in_relation_to_id, presence: true
validates :in_relation_to_type, presence: true
belongs_to :owner, polymorphic: true
belongs_to :in_relation_to, polymorphic: true
end
end
So, in your User model, you would say something like:
class User < ActiveRecord::Base
has_many :owned_relationships,
as: :owner,
class_name: "ActsAsRelatingTo::Relationship",
dependent: :destroy
has_many :organizations_i_relate_to,
through: :owned_relationships,
source: :in_relation_to,
source_type: "Organization"
...
end
I believe you may be able to leave the source_type argument off since the joined class (Organization) can be inferred from :organizations. Often, I'm joining models where the class name cannot be inferred from the relationship name, in which case I include the source_type argument.
With this, you can say user.organizations_i_relate_to. You can do the same set up for a relationship between any set of classes.
You could also say in your Organization class:
class Organization < ActiveRecord::Base
has_many :referencing_relationships,
as: :in_relation_to,
class_name: "ActsAsRelatingTo::Relationship",
dependent: :destroy
has_many :users_that_relate_to_me,
through: :referencing_relationships,
source: :owner,
source_type: "User"
So that you could say organization.users_that_relate_to_me.
I got tired of having to do all the set up, so in my gem I created an acts_as_relating_to method so I can do something like:
class User < ActiveRecord::Base
acts_as_relating_to :organizations, :teams
...
end
and
class Organization < ActiveRecord::Base
acts_as_relating_to :users, :organizations
...
end
and
class Team < ActiveRecord::Base
acts_as_relating_to :organizations, :users
...
end
and all the polymorphic associations and methods get set up for me "automatically".
Sorry for the long answer. Hope you find something useful in it.
I have model relationships like so:
class User
include Mongoid.Document
has_many :favorite_shows
end
class FavoriteShow
include Mongoid.Document
belongs_to :user
belongs_to :show
end
class Show
include Mongoid.Document
has_many :favorite_shows
end
FavoriteShow is a join table between users and shows with both the user_id and show_id as foreign keys. I keep getting the following error despite the fact that these foreign keys already exist:
Problem:
When adding a(n) Show to User#favorite_shows, Mongoid could not determine the inverse foreign key to set. The attempted key was 'user_id'.
Summary:
When adding a document to a relation, Mongoid attempts to link the newly added document to the base of the relation in memory, as well as set the foreign key to link them on the database side. In this case Mongoid could not determine what the inverse foreign key was.
Resolution:
If an inverse is not required, like a belongs_to or has_and_belongs_to_many, ensure that :inverse_of => nil is set on the relation. If the inverse is needed, most likely the inverse cannot be figured out from the names of the relations and you will need to explicitly tell Mongoid on the relation what the inverse is.
Example:
class Lush
include Mongoid::Document
has_one :whiskey, class_name: "Drink", inverse_of: :alcoholic
end
class Drink
include Mongoid::Document
belongs_to :alcoholic, class_name: "Lush", inverse_of: :whiskey
end
Now I've tried adding both inverse_of: nil to the associations, as well as the following with no luck:
class User
include Mongoid.Document
has_many :favorite_shows, class_name: "FavoriteShow", inverse_of: :user
end
class FavoriteShow
include Mongoid.Document
belongs_to :user, class_name: "User", inverse_of: :favorite_shows
belongs_to :show, class_name: "Show", inverse_of: :favorite_shows
end
class Show
include Mongoid.Document
has_many :favorite_shows, class_name: "FavoriteShow", inverse_of: :favorite_shows
end
I have these relationships working perfectly in ActiveRecord, but when switching over to Mongoid, I'm still unclear how the exact relationship is supposed to be translated. Any help would be really appreciated!
When using a document based database such as MongoDB you don't have a need for join tables like you would with a relational database. I suggest a structure like the one below:
class User
include Mongoid::Document
include Mongoid::Timestamps
has_and_belongs_to_many :favorite_shows, class_name: "Show", inverse_of: :users
end
class Show
include Mongoid::Document
include Mongoid::Timestamps
has_and_belongs_to_many :users, class_name: "User", inverse_of: :favorite_shows
end