I am struggling with an issue in my data model. I do have the following models:
class User < ActiveRecord::Base
...
has_many :claims #user-claims
has_many :claims, through: :rulings, as: :commissars
...
end
class Claim < ActiveRecord::Base
...
belongs_to :user
has_many :users, through: :rulings, as: :commissars
...
end
class Ruling < ActiveRecord::Base
belongs_to :user
belongs_to :claim
end
Error:
undefined method `commissars' for #<Claim:0xc5ac090>
Model Explanation:
User can write claims (A claim belongs to one user), and users could do the role of commissars to do the ruling of the claim (max numbers of commissars = 3 per claim).
Is there any way to fix this or improve the relationship?
This domain model requires som pretty complex relations so there is no shame in not getting it on the first try.
Lets start with user and claims:
class User < ActiveRecord::Base
has_many :claims, foreign_key: 'claimant_id',
inverse_of: :claimant
end
class Claim < ActiveRecord::Base
belongs_to :claimant, class_name: 'User',
inverse_of: :claims
end
This is a pretty basic one to many relation with a twist. Since User will have a bunch of relations to Claim we call the relation something other than the default user so that the nature of the relation is defined.
The class_name: 'User' option tells ActiveRecord to load the class User and use it to figure out what table to query and also what class to return the results as. Its needed whenever the class name cannot be directly derived from the name of the association. The option should be a string and not a constant due to the way Rails lazily resolves class dependencies.
Now lets add the commissar role. We will use ruling as the join table:
class Ruling < ActiveRecord::Base
belongs_to :claim
belongs_to :commissioner, class_name: 'User'
end
Notice that here we have a relation to User that we call commissioner for clarity. Now we add the relations to Claim:
class Claim < ActiveRecord::Base
belongs_to :claimant, class_name: 'User',
inverse_of: :claims
has_many :rulings
has_many :commissioners, through: :rulings
end
Then we need to setup the relations on the User side:
class User < ActiveRecord::Base
has_many :claims, foreign_key: 'claimant_id',
inverse_of: :claimant
# rulings as claimant
has_many :rulings, through: :claims
has_many :rulings_as_commissioner, class_name: 'Ruling',
foreign_key: 'commissioner_id'
has_many :claims_as_commissioner, through: :rulings_as_commissioner,
source: :claim
end
Note the source: :claim option where we tell ActiveRecord which party we want from the join table.
Of course for this to work we need to setup the columns and the foreign keys properly. These migrations are to create the tables from scratch but you can easily rewrite them to alter your existing tables:
class CreateClaims < ActiveRecord::Migration
def change
create_table :claims do |t|
t.belongs_to :claimant, index: true, foreign_key: false
t.timestamps null: false
end
# we need to setup the fkey ourself since it is not conventional
add_foreign_key :claims, :users, column: :claimant_id
end
end
class CreateRulings < ActiveRecord::Migration
def change
create_table :rulings do |t|
t.belongs_to :claim, index: true, foreign_key: true
t.belongs_to :commissioner, index: true, foreign_key: false
t.timestamps null: false
end
add_foreign_key :rulings, :users, column: :commissioner_id
add_index :rulings, [:claim_id, :commissioner_id], unique: true
end
end
max numbers of commissars = 3 per claim
This is not really part of the associations rather you would enforce this rule by adding a validation or an association callback.
class Ruling < ActiveRecord::Base
# ...
validate :only_three_rulings_per_claim
private
def only_three_rulings_per_claim
if claim.rulings.size >= 3
errors.add(:claim, "already has the max number of commissars")
end
end
end
See:
Rails Guides: Active Record Migrations
Rails Guides: the has_many though: relations
First, I would suggest you go back and read the Guide carefully as I believe you have fundamentally misunderstood a number of things. The as: option, for instance, does not indicate role but, rather, the presence of a polymorphic join. Also, you can't declare has_many :claims twice on the same model. Anyway, go give it another read.
But, to your question - a functional although somewhat inelegant approach might look like:
class User < ActiveRecord::Base
...
has_many :claims
has_many :claim_commissars, foreign_key: "commissar_id"
has_many :commissar_claims, through: :claim_commissars, class_name: "Claim"
# ^^^^^^^^^^^^^^^^^^^^^
# this bit may be wrong
...
end
class Claim < ActiveRecord::Base
...
belongs_to :user
has_one :ruling
has_many :claim_commissars
has_many :commissars, through: :claim_commissars
...
end
class ClaimCommissar < ActiveRecord::Base
...
belongs_to :claim
belongs_to :commissar, class_name: "User"
...
end
class Ruling < ActiveRecord::Base
...
belongs_to :claim
belongs_to :commissar, class_name: "User"
...
end
You would need to enforce your 'max 3 commissars` in the code.
This is not tested and you will likely need to fiddle with it to get it to go. But, hopefully, it sets you in a better direction.
Good luck!
Related
I am building a Ruby on Rails 6 application where I have a model Archive, and a another model ArchiveAgencies. In the Archive model I must have a sender agency and a receiver agency, which should represent ArchiveAgencies.
After going through the Rails docs, and some StackOverflow QA:
How do I add migration with multiple references to the same model in one table? Ruby/Rails
Defining two references to the same column in another table
Ruby on Rails: two references with different name to the same model
I came up with this approach:
Models
class Archive < ActiveRecord::Base
belongs_to :sender_agency, class_name: ArchiveAgencies, foreign_key: "sender_agency_id"
belongs_to :receiver_agency, class_name: ArchiveAgencies, foreign_key: "receiver_agency_id"
end
class ArchiveAgency < ActiveRecord::Base
has_many :archives, inverse_of: 'sender_agency'
has_many :archives, inverse_of: 'receiver_agency'
end
Migration
class CreateArchiveAgencies < ActiveRecord::Migration[6.0]
def change
create_table :archives do |t|
t.string :name
t.timestamps
end
end
end
class CreateArchives < ActiveRecord::Migration[6.0]
def change
create_table :archives do |t|
t.references :sender_agency, foreign_key: { to_table: :archive_agencies }
t.references :receiver_agency, foreign_key: { to_table: :archive_agencies }
t.timestamps
end
end
end
Is this the best approach for this case?
Would, having two inverse_of statements in the model ArchiveAgency work?
If you declare multiple associations with the same name the last one will overwrite the others.
Instead you need to use unique names for each association and configure them properly:
class ArchiveAgency < ActiveRecord::Base
has_many :archives_as_sender,
inverse_of: :sender_agency,
foreign_key: :sender_agency_id,
class_name: 'Archive'
has_many :archives_as_receiver,
inverse_of: :receiver_agency,
foreign_key: :receiver_agency_id,
class_name: 'Archive'
end
class Archive < ActiveRecord::Base
belongs_to :sender_agency, # foreign_key can be derived from the name
class_name: 'ArchiveAgency', # needs to be a string - not the class itself
inverse_of: :archives_as_sender
belongs_to :receiver_agency,
class_name: 'ArchiveAgency'
inverse_of: :archives_as_receiver
end
In my Post model, I have
has_many :followers
In my Follower model, I have
belongs_to :model
belongs_to :owner,polymorphic: true
In my User and Admin devise models, I have
has_many :followers,as: :owner
Requirement: I want to have something like Post.owners and it should return me a list of all users and/or admins that are following this post.
I'm not sure, but I think that AR doesn't provide a way to load polymorphic associations in just one query. But you can use:
post = Post.find(1)
post_followers = post.followers.includes(:owner)
post_owners = post_followers.map(&:owner)
The solution you're looking for is polymorphic has many through. You can add these lines in your model of User and Admin.
has_many :followers
has_many :posts, through: :followers, source: :owner, source_type: 'Owner'
I think you want something like this:
class Post < ApplicationRecord
belongs_to :owner, polymorphic: true
end
class User < ApplicationRecord
has_many :posts, as: :owner
end
class Follower < ApplicationRecord
has_many :posts, as: :owner
end
From an instance of your User you can then retrieve their posts with #user.posts
The same goes for your Follower, #follower.posts
If you want to get to the parent of your post instance, you can do so via #post.owner. To make this work, however, we need to set up the schema correctly by declaring both a foreign key column and a type column in the model that declares the polymorphic interface using the references form:
class CreatePosts < ActiveRecord::Migration[5.0]
def change
create_table :posts do |t|
# your attribs here
t.references :owner, polymorphic: true, index: true
end
end
end
I'm not sure how to create this, I'd like to create a many-to-many polymorphic association.
I have a question model, which belongs to a company.
Now the question can has_many users, groups, or company. Depending on how you assign it.
I'd like to be able to assign the question to one / several users, or one / several groups, or the company it belongs to.
How do I go about setting this up?
In this case I would add a Assignment model which acts as an intersection between questions and the entities which are assigned to it.
Create the table
Lets run a generator to create the needed files:
rails g model assignment question:belongs_to assignee_id:integer assignee_type:string
Then let's open up the created migration file (db/migrations/...__create_assignments.rb):
class CreateAssignments < ActiveRecord::Migration
def change
create_table :assignments do |t|
t.integer :assignee_id
t.string :assignee_type
t.belongs_to :question, index: true, foreign_key: true
t.index [:assignee_id, :assignee_type]
t.timestamps null: false
end
end
end
If you're paying attention here you can see that we add a foreign key for question_id but not assignee_id. That's because the database does not know which table assignee_id points to and cannot enforce referential integrity*. We also add a compound index for [:assignee_id, :assignee_type] as they always will be queried together.
Setting up the relationship
class Assignment < ActiveRecord::Base
belongs_to :question
belongs_to :assignee, polymorphic: true
end
The polymorpic: true option tells ActiveRecord to look at the assignee_type column to decide which table to load assignee from.
class User < ActiveRecord::Base
has_many :assignments, as: :assignee
has_many :questions, through: :assignments
end
class Group < ActiveRecord::Base
has_many :assignments, as: :assignee
has_many :questions, through: :assignments
end
class Company < ActiveRecord::Base
has_many :assignments, as: :assignee
has_many :questions, through: :assignments
end
Unfortunately one of the caveats of polymorphic relationships is that you cannot eager load the polymorphic assignee relationship. Or declare a has_many :assignees, though: :assignments.
One workaround is:
class Group < ActiveRecord::Base
has_many :assignments, as: :assignee
has_many :questions, through: :assignments
def assignees
assignments.map(&:assignee)
end
end
But this can result in very inefficient SQL queries since each assignee will be loaded in a query!
Instead you can do something like this:
class Question < ActiveRecord::Base
has_many :assignments
# creates a relationship for each assignee type
['Company', 'Group', 'User'].each do |type|
has_many "#{type.downcase}_assignees".to_sym,
through: :assignments,
source: :assignee,
source_type: type
end
def assignees
(company_assignees + group_assignees + user_assignees)
end
end
Which will only cause one query per assignee type which is a big improvement.
I have this User and team model which has the following association:
user.rb
class User < ActiveRecord::Base
belongs_to :team
team.rb
class Team < ActiveRecord::Base
has_many :users
has_one :leader, class_name: "User", foreign_key: "leader_id"
belongs_to :manager, class_name: "User", foreign_key: "manager_id"
but it seems that I can't imagine representing it properly into a migration. At first, this is what I did:
class AddTeamIdToUsers < ActiveRecord::Migration
def change
add_column :users, :team_id, :integer
add_index :users, :team_id
end
end
class AddUsersToTeams < ActiveRecord::Migration
def change
add_reference :teams, :leader, index: true
add_reference :teams, :manager, index: true
end
end
for sure, what I did on AddTeamToIdUsers was a many-to-one association since a Team can have many Users, but the leader position should only be exclusive for a specific team only (same goes to members as well, they should not belong to other teams). Managers, however, can have many teams to manage. Going back to my concern, how can I represent my scenario into a migration? Or are there any adjustments I should make in my associations? After the necessary adjustments and solutions considered, will the application automatically follow the association rules upon adding/updating teams?
Your migrations look correct, but your associations are not complete:
class User < ActiveRecord::Base
belongs_to :team
has_one :leading_team, class_name: 'Team', foreign_key: 'leader_id'
has_many :managed_teams, class_name: 'Team', foreign_key, 'manager_id'
class Team < ActiveRecord::Base
has_many :users
belongs_to :leader, class_name: "User"
belongs_to :manager, class_name: "User"
And you should be all set.
Because a manager can have multiple teams, but is still "part of" the team, I'd suggest creating a join table for users and teams. We'll call it members. It will reference both user and team.
class CreateMembers < ActiveRecord::Migration
def change
create_table :members do |t|
t.references :user
t.references :team
t.timestamps
end
end
end
Then, we'll need add the members association to the User model. Users will have many members, and, because of managers, have many teams as well. I've also included a function to get the team of a worker or leader, since there's only one.
class User < ActiveRecord::Base
has_many :members
has_many :teams, through: members, dependent: destroy
validates_associated :members # More on this later
# for workers and leaders
def team
self.teams.first
end
end
Similar to the User model, we'll need to add the members association to the Team model. We'll also include a few functions to get the leader and manager of a team, and validation to make sure a team has exactly one leader and one manager.
class Team < ActiveRecord::Base
has_many :members
has_many :users, through: :members, dependent: destroy
validate :has_one_leader_and_manager
validates_associated :members # More on this later
def manager
self.users.where(type: 'manager').first
end
def leader
self.users.where(type: 'leader').first
end
def has_one_leader_and_manager
['leader', 'manager'].each do |type|
unless self.users.where(type: type).count == 1
errors.add(:users, "need to have exactly one #{type}")
end
end
end
end
Lastly, we'll set up the Member model. We can also include some validation to ensure that a team can only have one leader and one manager, and that workers and leader cannot belong to more than one team.
class Member < ActiveRecord::Base
belongs_to :user
belongs_to :team
validate :team_has_one_leader_and_manager
# Make sure player (worker or leader) is only on one team
validates :user_id, uniqueness: true, if: :is_player?
def is_player?
['worker', 'leader'].include? user.type
end
def team_has_one_leader_and_manager
if ['leader', 'manager'].include?(user.type)
if team.users.where('type = ? AND id != ?' user.type, user_id).count.any?
errors.add(:team, "can't add another #{user.type}")
end
end
end
end
Note that with the validation methods, you may want to move them around and/or refactor them, depending on how you add users and team, and how you'll add new members. However, this answer will hopefully give you enough information to get started.
I'm in the process of building a back-end admin panel for our customers.
I'm integrating a feature to allow users to upgrade and downgrade their monthly subscription which means adding a new model for the billing_plans table.
I'm stuck trying to get the relationship right between an account and a plan.
I have a billing_plan model:
class BillingPlan < ActiveRecord::Base
self.table_name = "billing_plans"
has_many :accounts, primary_key: 'name', foreign_key: 'audio_billing_model'
end
and an accounts model:
class Account
has_many :contacts
belongs_to :user, primary_key: :email, foreign_key: :billing_email_address
has_one :billing_plan, foreign_key: 'name', primary_key: 'audio_billing_model'
end
I'm sure this could help other people and I'm pretty certain someone must have come across it before.
Since you're trying to establish a has_many belongs_to relationship, simply define the primary key on the has_many model, then direct the belongs_to model to utilize that primary key as its foreign key:
# app/models/billing_plan.rb
class BillingPlan < ActiveRecord::Base
self.table_name = "billing_plans" # Seems unnecessary, as the table name by default is `billing_plans`
has_many :accounts, primary_key: 'name'
end
# app/models/account.rb
class Account < ActiveRecord::Base # Remember to subclass `ActiveRecord::Base`
has_many :contacts
belongs_to :user, primary_key: :email, foreign_key: :billing_email_address
has_one :billing_plan, foreign_key: 'name'
end